4

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)
GhostCat
  • 137,827
  • 25
  • 176
  • 248
RandomWanderer
  • 701
  • 2
  • 12
  • 23

1 Answers1

4

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().

glytching
  • 44,936
  • 9
  • 114
  • 120