When using Mockito, it is often said that "whether a method is called" is verified using the verify times (), but the argument (contents of the object) passed to the method is verified. Is there a way to do it? I thought and examined it.
https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentMatchers.html https://www.codeflow.site/ja/article/mockito-argument-matchers
Create a custom Matcher by inheriting from 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 and get all the contents of the map out will make it easier if the test fails.
@Override
public String toString() {
//You can choose how you want 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();
}
}
Pass a custom Matcher to org.mockito.ArgumentMatchers.argThat and use it.
HogeTest.java
// hoge.save(map);Is called to verify that its arguments are the same as the expected value
verify(hoge,atLeastOnce()).save(argThat(new HashMapMatcher(map)));
It seems that it can be used not for verify but for verification at when ~ then Return. Let's enjoy test life.
Recommended Posts