Mockito/PowerMockito - 模拟接收 Lambda 表达式作为参数的方法

Mockito/PowerMockito - Mock a method that receives Lambda expression as a parameter

我想模拟下面的方法。但是对于使用 Java.util.Function.

的第二个参数,我没有找到任何 Mockito.Matchers
public List<String> convertStringtoInt(List<Integer> intList,Function<Integer, String> intToStringExpression) {
        return intList.stream()
                .map(intToStringExpression)
                .collect(Collectors.toList());
    }

我正在寻找这样的东西:

Mockito.when(convertStringtoInt(Matchers.anyList(),Matchers.anyFunction()).thenReturn(myMockedList)

如果您只想模拟 Function 参数,则可以使用以下任一方法:

Mockito.when(convertStringtoInt(Matchers.anyList(), Mockito.any(Function.class))).thenReturn(myMockedList);

Mockito.when(convertStringtoInt(Matchers.anyList(), Mockito.<Function>anyObject())).thenReturn(myMockedList);

给定 class、Foo,其中包含方法:public List<String> convertStringtoInt(List<Integer> intList,Function<Integer, String> intToStringExpression) 以下测试用例通过:

@Test
public void test_withMatcher() {
    Foo foo = Mockito.mock(Foo.class);

    List<String> myMockedList = Lists.newArrayList("a", "b", "c");

    Mockito.when(foo.convertStringtoInt(Matchers.anyList(), Mockito.<Function>anyObject())).thenReturn(myMockedList);

    List<String> actual = foo.convertStringtoInt(Lists.newArrayList(1), new Function<Integer, String>() {
        @Override
        public String apply(Integer integer) {
            return null;
        }
    });

    assertEquals(myMockedList, actual);
}

注意:如果您真的想调用和控制 Function 参数的行为,那么我认为您需要查看 thenAnswer()