Search code examples
javaunit-testingmockitohamcrest

Mockito - comma verify argument with comma separated list without order


My Mockito version isn't the newest -version 1.10.19

I have a method in my DAO class I want to test, for example

public void updateMe(String commaSeparatedAttributes)

It get a string as argument with comma separated list as 2,5,3

The problem is that the order of the list isn't guaranteed.

I found this solution with Hamcrest containsInAnyOrder, but this doesn't help me because the argument is a String, I tried several options (including sending ArrayList) as:

verify(dao).updateMe(argThat(Matchers.containsInAnyOrder("2","5,"3")));

This isn't compiling with error:

Type mismatch: cannot convert from Iterable<capture#1-of ? extends String> to String

EDIT

Also the following return NullPointerException in test

verify(dao).updateMe(argThat( 
new ArgumentMatcher<String>() { 
@Override 
public boolean matches(Object argument) { 
List<String> inputs = Arrays.asList(((String)argument).split(",")); 
return inputs.containsAll(Arrays.asList("2", "5", "3")); 
} 
} 
));

Solution

  • Your updateMe method takes a String. The matcher used in your verify expects a Collection. You may be better off writing a custom matcher.

    You'll first need to break your comma separated String into a List of Strings.

    Then use List::containsAll with your expectations passed in.

    verify(dao).updateMe(argThat(t -> {
        List<String> inputs = Arrays.asList(t.split(","));
        return inputs.containsAll(Arrays.asList("2", "5", "3"));
    }));