Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a matcher that is not equal to something

I am trying to create a mock for a call. Say I have this method I am trying to stub out:

class ClassA {   public String getString(String a) {     return a + "hey";   } } 

What I am trying to mock out is: 1st instance is

when(classA.getString(eq("a")).thenReturn(...);` 

in the same test case

when(classA.getString([anything that is not a])).thenReturn(somethingelse); 

The 2nd case is my question: How do I match anyString() other than "a"?

like image 817
Churk Avatar asked Sep 26 '14 19:09

Churk


People also ask

What is EQ Mockito?

Mockito Argument Matcher - eq() When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method. when(mockFoo. bool(eq("false"), anyInt(), any(Object. class))).


2 Answers

With Mockito framework, you can use AdditionalMatchers

ClassA classA = Mockito.mock(ClassA.class); Mockito.when(classA.getString(Matchers.eq("a"))).thenReturn("something");  Mockito.when(classA.getString(AdditionalMatchers.not(Matchers.eq("a")))).thenReturn("something else"); 

Hope it helps.

like image 151
troig Avatar answered Sep 22 '22 04:09

troig


Use argThat with Hamcrest:

when(classA.getString(argThat(CoreMatchers.not(CoreMatchers.equalTo("a")))... 

You might also be able to do this via ordering. If you put one when(anyString) and when(eq("a")) in the correct order, Mockito should test them in order and do the "a" logic when appropriate and then "anyString" logic otherwise.

like image 28
John B Avatar answered Sep 24 '22 04:09

John B