For reference, be aware that Hamcrest matchers and Mockito matchers behave very differently. Hamcrest's stateless Matcher objects represent the match function as an instance, and can be wrapped to invert their results; Mockito's "registered matchers" work only via side-effects.
argThat
adapts a Hamcrest matcher into a Mockito matcher, Hamcrest's CoreMatchers.not
inverts a Hamcrest matcher, and Mockito's AdditionalMatchers.not
inverts a Mockito matcher (via side-effects). This is part of the reason that CoreMatchers.not
always returns a Matcher<T>
, while AddionalMatchers.not
returns an arbitrary T
; it's operating on Mockito state you can't see.
This gives you the following behavior:
// BAD: Don't use AdditionalMatchers to invert a Hamcrest matcher.
doReturn(false).when(mock).addAll(
Mockito.argThat(AdditionalMatchers.not(new IsListOf2Elements())));
// GOOD: Use AdditionalMatchers to invert a Mockito matcher. (See ericj's answer.)
doReturn(false).when(mock).addAll(
AdditionalMatchers.not(Mockito.argThat(new IsListOf2Elements())));
// ALSO GOOD: Use CoreMatchers to invert a Hamcrest matcher. (See troig's answer.)
doReturn(false).when(mock).addAll(
Mockito.argThat(CoreMatchers.not(new IsListOf2Elements())));
If the exception you're making is about stubbed behavior, you can also use a more-specific override to stub the general behavior in addition to the specific exception.