Search code examples
javamockingmockitoverify

Mockito verify argument contains another string ignoring case


What I've got is this line:

verify( mockAppendable ).append( org.mockito.Mockito.contains( msg ) );

... but I want this test to be case-indifferent. How would I do that?


Solution

  • On the page, what do they mean by "you can extract method" and is it possible to use a Java 8 lambda to make this a one-liner?

    In a single line using case insensitivity code from here:

    verify(mockAppendable)
        .append(
           argThat(arg ->
             Pattern.compile(Pattern.quote(msg), Pattern.CASE_INSENSITIVE).matcher(arg).find()));
    

    So they allowed the lambda version by skipping specifying a custom error message.

    And by "you can extract a method", they mean:

    verify(mockAppendable).append(argThat(containsCaseInsensitive(msg)));
    

    And the method is defined as:

    public static ArgumentMatcher<String> containsCaseInsensitive(final string s) {
        if (s == null) throw new IllegalArgumentException("s is null");
        final Pattern pattern = Pattern.compile(Pattern.quote(s), Pattern.CASE_INSENSITIVE);
        return new ArgumentMatcher<String>() {
    
            @Override
            public boolean matches(String arg) {
                return arg != null && pattern.matcher(arg).find();
            }
    
            @Override 
            public String toString() {
                return String.format("[should have contained, ignoring case, \"%s\"]", s);
            }
        };
    }
    

    That's completely reusable, you can put that inside a new class like MocitoMatchers for example and call from many tests just like any of the built-in matchers.