[Java] Validate the contents of the argument object with Mockito

1 minute read

When using Mockito, we often hear that “whether a method is called” is verified using times() of verify, but the argument (contents of the object) passed to the method is verified. Is there a way to do it? I thought it out and searched.

Reference

https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentMatchers.html https://www.codeflow.site/ja/article/mockito-argument-matchers

How to make a Matcher

Create a custom Matcher by inheriting org.mockito.ArgumentMatcher. HashMap would look like this.

HashMapMatcher.java


import java.util.HashMap;

import org.mockito.ArgumentMatcher;

public class HashMapMatcher implements ArgumentMatcher<HashMap<String, String>> {
HashMap<String, String> map;

    public HashMapMatcher(HashMap<String, String> map) {
        this.map = map;
    }

    @Override
    public boolean matches(HashMap<String, String> actual) {
if (this.map.keySet().size() != actual.keySet().size()) {
    return false;
    }
    for (String key :this.map.keySet()) {
    if (!actual.containsKey(key)) {
    return false;
    }
    if (!this.map.get(key).equals(actual.get(key))) (
    return false;
    }
    }
        return true;
    }
    
    // Override so that the contents of the map are all output, it will be easier if the test fails.
    @Override
    public String toString() {
    // You can choose how to output it.
    StringBuffer sb = new StringBuffer();
    for (String key :this.map.keySet()) {
    sb.append("[key:").append(key);
    sb.append(", value:").append(map.get(key)).append("]");
    }
    return sb.toString();
    }

}

How to use

Pass a custom Matcher to org.mockito.ArgumentMatchers.argThat and use it.

HogeTest.java


// hoge.save(map); is called and verifies that its argument is the same as expected value
verify(hoge,atLeastOnce()).save(argThat(new HashMapMatcher(map)));

At the end

It seems that it can be used not only for verify but also for verification from when to then Return. Let’s enjoy test life.