Home > other >  Mockito ArgumentMatcher to verify if arg value is contained in a certain collection
Mockito ArgumentMatcher to verify if arg value is contained in a certain collection

Time:11-24

Is there a way, using Mockito to define an expression like this?

when(mockObject.getValuesFor(in(1, 2, 3)).thenReturn(List.of(...)));

I can't find a method like in() among the ones defined in ArgumentMatchers and AdditionalMatchers, so I'd like to know which is a common way to achieve what I need.

Note The method I'm mocking is declared like this:

List<Integer> getValuesFor(int arg) {...}

CodePudding user response:

I couldn't find one. So I use below workaround.

List list = List.of(1, 2, 3);
when(mockObject.getValuesFor(list).thenReturn(List.of(...)));

//do actual test method call

ArgumentCaptor<List> listCaptor = ArgumentCaptor.class(List.class);
verify(mockObject).getValuesFor(listCaptor.capture());

assertEquals(3, list.getValue().size());
assertEquals(1, list.getValue().get(0));
assertEquals(2, list.getValue().get(1));
assertEquals(3, list.getValue().get(2));

It essentially does the same thing. If same list was not passed as the method argument, test case will fail in assert statements.

CodePudding user response:

I think intThat gets close to what you need:

when(mockObject.getValuesFor(intThat(x -> Set.of(1, 2, 3).contains(x))))
  .thenReturn(List.of(3, 4, 5));

In addition, you can extract a method producing inner ArgumentMatcher<Integer>, which would make your code look like

when(mockObject.getValuesFor(intThat(isOneOf(1, 2, 3))))
  .thenReturn(List.of(3, 4, 5));
  • Related