如何使用函数式接口参数模拟方法?

Bha*_*thi 5 java unit-testing mockito

在 Mockito 中,如何模拟将函数接口作为方法参数的方法?例如:

String foo(String m, Function<Double, Options> r) {}

Kev*_*ker 6

以下尚未经过编译测试/运行,可能有小错误。我知道它有针对通用的警告

class Foo {
    String foo(String m, Function<Double, Options> r) {}
}

class Bar {
    Foo myFoo; // assume this is normally injected or something

    boolean works() {
        // ... code that somehow uses myFoo and processes the String returned
    }
}

class BarTestCase {
    @Mock private Foo foo;
    @InjectMocks private Bar bar

    @Test
    public void testFooMethod() {
        when(foo.foo(anyString(), any(Function.class)).thenReturn("ABCD1234");
        assertTrue(bar.works());
    }
}
Run Code Online (Sandbox Code Playgroud)