Mockito verify method was called with set, that contains specific value

me1111 picture me1111 · Apr 16, 2014 · Viewed 13.9k times · Source

I want to be sure that mocked is called with specific set of strings as parameter. For example, I have the following code:

public class SomeLogic {
    @Autowired
    private SpecificService specificService;

    public void action() {
        Set<String> args = fillArgsMethod();
        specificService.handleArgs(args);
    }
}

And my current try to test it is the following

@Mock
private SpecificService specificService
@InjectMocks
private SomeLogic someLogic;

@Test
public void testAction() {
    someLogic.action();
    verify(specificService).handleArgs(anySet());
}

But I want to be sure, that handleArgs() will receive the exact set of strings, that I expect. How can I modify verifying to check that handleArgs is called with set "first","second"? Thanks

Answer

geoand picture geoand · Apr 16, 2014

Isah gave a valid answer, but I want to turn your attention to a more general feature of Mockito which is ArgumentCaptor

In you case you would do something along the following lines:

Class<HashSet<String>> setClass = (Class<HashSet<String>>)(Class)HashSet.class;
ArgumentCaptor<Set<String>> setCaptor= ArgumentCaptor.forClass(setClass .class);

verify(specificService).create(setCaptor.capture());
HashSet<String> capturedSet = setCaptor.getValue();

//do whatever test you want with capturedSet