Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: Match any String except one [duplicate]

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.

like image 762
Stephan Avatar asked May 07 '15 17:05

Stephan


2 Answers

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

like image 163
troig Avatar answered Nov 17 '22 09:11

troig


The solution I used:

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

// ...

argThat(not("ExceptionString"))

Versions

  • Mockito 3.3.3
  • Hamcrest 1.3
like image 40
Stephan Avatar answered Nov 17 '22 09:11

Stephan