Search code examples
javajunitmockitomatcher

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"?


Solution

  • 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.