15

How can I write a matcher using Mockito that matches any string except a specific one?

I have tried using some hamcrest matchers to negate and combine other matchers, but the hamcrest matchers all return values of type Matcher<T> which dont work very well with Mockito matchers.

Stephan
  • 16,509
  • 7
  • 35
  • 61
  • 1
    Use `argThat(yourHamcrestMatcher)`. http://docs.mockito.googlecode.com/hg/org/mockito/Matchers.html – JB Nizet May 07 '15 at 17:07
  • @JBNizet i assume that works because `argThat(matcher())` essentially converts the return type from `Matcher` to ``? – Stephan May 07 '15 at 17:14
  • 1
    @JNNizet: the url of the docs is now http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html – Jmini Jun 08 '16 at 08:44

2 Answers2

24

Just point that with Mockito you can also use AdditionalMatchers and ArgumentMatchers

import static org.mockito.AdditionalMatchers.not;
import static org.mockito.ArgumentMatchers.eq;

//anything but not "ejb"    
mock.someMethod(not(eq("ejb")));

According its documentation:

Example of using logical and(), not(), or() matchers:

//anything but not "ejb"
mock.someMethod(not(eq("ejb")));

There is more info in this other SO question

Hope it helps

Community
  • 1
  • 1
troig
  • 7,072
  • 4
  • 37
  • 63
16

The solution I used:

import static org.hamcrest.CoreMatchers.not;
import static org.mockito.ArgumentMatchers.argThat;

// ...

argThat(not("ExceptionString"))

Versions

Stephan
  • 41,764
  • 65
  • 238
  • 329
Stephan
  • 16,509
  • 7
  • 35
  • 61