How to write a matcher that is not equal to something

JavaJunitMockitoMatcher

Java Problem Overview


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

Java Solutions


Solution 1 - Java

With Mockito framework, you can use [AdditionalMatchers][1]

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. [1]: https://static.javadoc.io/org.mockito/mockito-core/2.23.0/org/mockito/AdditionalMatchers.html

Solution 2 - Java

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.

Solution 3 - Java

In mockito the last stubbing is the most important. This means that you can simply use the standard matchers for your needs:

// "Default" return values.
when(classA.getString(ArgumentMatchers.anyString())).thenReturn(somethingelse);
// Specific return value for "a"
when(classA.getString(ArgumentMatchers.eq("a"))).thenReturn(something);

Note that you have to use ArgumentMatchers for both since you're mixing them.

Solution 4 - Java

I actually took this approach after carefully looking at the suggested answers:

doAnswer(new Answer<String>() {
  public String answer(InvocationOnMock invocation) throws Throwable {
    String originalParam = (String) invocation.getArguments()[0];
    return StringUtils.equalsIgnoreCase(originalParam, "a") ? "Something" : "Something Else";
  }
}).when(classA).getString(anyString());

This allows me to handle more than just two cases by adjusting the return base on the params.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChurkView Question on Stackoverflow
Solution 1 - JavatroigView Answer on Stackoverflow
Solution 2 - JavaJohn BView Answer on Stackoverflow
Solution 3 - JavaPieter De BieView Answer on Stackoverflow
Solution 4 - JavaChurkView Answer on Stackoverflow