How do I generate a custom message from a custom Mockito ArgumentMatcher?
I'm writing an ArgumentMatcher and the guts of the comparison come down to something like:
return A.value().equals(B.value()) && A.name().equals(B.name());
Unfortunately, when the doesn't pass, Mockito just tells me it failed. I want to add a custom message like "Values don't match" or "Names don't match" (of course I'd like to give more info, but until I can figure out this simple case, w开发者_运维问答hat's the point of going any further).
Previously (before working with Mockito), I remember matchers having two methods - one to check the match and one to generate a failure message (true, it was a pain to write both methods, but I miss the second method now).
Any idea how to do this? Any help is appreciated!
I get it now. Hamcrest provides a "describeTo" method. This is equivalent to the method I remember from EasyMock. You simply add your error conditions to the Description object, and viola, you have a better failure message.
A general way of providing custom messages is through Mockito.description()
method:
verify(writer, never().description("exception was thrown"))
.println(any(Object.class));
If you are implementing the org.mockito.ArgumentMatcher
interface, the test will call its toString()
method to create the "Wanted" side of the comparison message. Implementing this method by simply returning the value of the toString()
method on the expected object used to initialize the ArgumentMatcher
will likely get you a useful message.
I am warping junit assert into argThat
verify(mockBuildingRepo, times(1))
.save(argThat(new ArgumentMatcher<Building>() {
@Override
public boolean matches(Building building) {
assertEquals("Test upload response", building.getName());
return true;
}
}));
It will give me meaningful message like
org.opentest4j.AssertionFailedError:
Expected :Test upload resp2onse
Actual :Test upload response
<Click to see difference>
精彩评论