I want to mock the following method. But I don't find any Mockito.Matchers
for the second parameter which uses Java.util.Function
.
public List<String> convertStringtoInt(List<Integer> intList,Function<Integer, String> intToStringExpression) {
return intList.stream()
.map(intToStringExpression)
.collect(Collectors.toList());
}
I am looking for something like this:
Mockito.when(convertStringtoInt(Matchers.anyList(),Matchers.anyFunction()).thenReturn(myMockedList)
If you only want to mock the Function argument then either of the following would work:
Mockito.when(convertStringtoInt(Matchers.anyList(), Mockito.any(Function.class))).thenReturn(myMockedList);
Mockito.when(convertStringtoInt(Matchers.anyList(), Mockito.<Function>anyObject())).thenReturn(myMockedList);
Given a class, Foo
, which contains the method: public List<String> convertStringtoInt(List<Integer> intList,Function<Integer, String> intToStringExpression)
the following test case passes:
@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);
}
Note: if you actually want to invoke and control the behaviour of the Function parameter then I think you'd need to look at thenAnswer().