In the test, the argument passed to the mock in the method operation setting and method call verification may be different from the argument actually passed from the test target class to the mock method. At this time, by using ArgumentMatcher, the contents of the argument can be verified softly.
--Validate only the type passed --Omit verification of arguments that have been verified in other test cases --Specify detailed conditions
There are uses such as.
For example, if you want to validate only the passed type, you can use the ArgumentMatchers.any method. It is also used to skip validation of arguments that have already been validated in other test cases.
Mockito.doNothing().when(display).display(ArgumentMatchers.any());
Mockito.verify(display, Mockito.times(1)).display(ArgumentMatchers.any());
Some of the basic types and collection types have corresponding any methods in advance, but you can also create them when verifying the type of your own class.
Mockito.doNothing().when(display).display(ArgumentMatchers.anyString());
Mockito.verify(display, Mockito.times(1)).display(ArgumentMatchers.any(String.class));
--Create an implementation class for the ArgumentMatcher interface. At this time, override the matches method. --In the method operation setting and method call verification, pass an instance of the above class to the argument of the argThat method of the Mockito class.
ArgumentMatcher<String> matcher = argument -> {
assertThat(argument.substring(1), is(msg));
return true;
};
Mockito.doNothing().when(display).display(Mockito.argThat(matcher));
Mockito.verify(display, Mockito.times(1)).display(Mockito.argThat(matcher));
The lambda expression is used in the above expression. The lambda expression is a further omission of the anonymous class description.
The override of the matches method of ArgumentMatcher is written using an anonymous class as follows.
ArgumentMatcher<String> matcher = new ArgumentMatcher(
@Override
public boolean matches(Object argument) {
assertThat(argument.substring(1), is(msg));
return true;
}
)
By using a lambda expression, you can:
--Omit new (because lambda expressions always create an instance) --Omit ArgumentMatcher (Here, it's obvious that you want to pass ArgumentMatcher to the implementation class of ArgumentMatcher. Maybe the variable type declaration works here) -Omit @Override, matches (The ArgumentMatcher interface has only one method. Both are obvious because we will create an implementation class for this.)
For practice, I will write the definition of ArgumentMatcher once again.
ArgumentMatcher<String> matcher = argument -> {
assertThat(argument.substring(1), is(msg));
return true;
};
Good job.
Recommended Posts