Mockito custom verify parameter Matcher, mockitomatcher
In TDD development, we may encounter some important Behavior tests without return values, such as adding user points in the user's point DB, this behavior has important value for our business, so we also hope to test and cover this part of business value. In this case, we need to use verify assertions brought by mockito, but verify's parameter assertions mainly include eq, or any common methods. Sometimes we also want to be able to assert some attributes of an object, such as the integral value above. User credits may be different for different scenarios.
Return to the Mockito parameter Matcher. Mockito provides ArgumentMatcher for us to extend Matcher. The following is a scenario for adding user credits:
public class Game { private String type; private int rate; public Game(String type, int rate) { this.type = type; this.rate = rate; } public String getType() { return type; } public int getRate() { return rate; } } public class GameDao { public void addRate(Game game) { //TODO: insert to db } }
We want to call addRate for verify GameDao and set the credit rate to a specific value.
So we can extend the ArgumentMatcher of Mockito:
public class PartyMatcher<T> extends ArgumentMatcher<T> { private Object value; private Function<T, Object> function; public PartyMatcher(Function<T, Object> getProperty, Object value) { this.value = value; this.function = getProperty; } @Override public boolean matches(Object o) { return (o instanceof Game) ? function.apply((T) o).equals(value) : false; } }
Therefore, our test can be as follows:
@ Test public void should_run_customer_mockito_matcher () throws Exception {final GameDao gameDao = mock (GameDao. class); gameDao. addRate (new Game ("sign in", 7); verify (gameDao ). addRate (argThat (new PartyMatcher <Game> (new Function <Game, Object> () {@ Override public Object apply (Game game) {return Game. getRate () ;}}, 7); verify (gameDao ). addRate (argThat (new PartyMatcher <Game> (new Function <Game, Object> () {@ Override public Object apply (Game game) {return Game. getType () ;}, "sign in ")));}
Mockito provides us with a lot of Matcher extension methods. This article is just an example of ArgumentMatcher.