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"?
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))).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With