I'm trying to verify that the class I'm testing calls the correct dependency class's method. So I'm trying to match the method parameters, but I don't really care about the actual values in this test, because I don't want to make my test brittle.
However, I'm running into trouble setting it up because Mockito has decided that the behaviour I'm expecting is a bug: https://github.com/mockito/mockito/issues/134
So what't the correct way to define an ArgumentMatcher
for a parameter that might be null
?
With issue #134 "fixed", this code fails because the matchers only match in the first case. How can I define a matcher to work in all 4 cases?
MyClass c = mock(MyClass.class); c.foo("hello", "world"); c.foo("hello", null); c.foo(null, "world"); c.foo(null, null); verify(c, times(4)).foo(anyString(), anyString());
Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments.
Argument matchers are mainly used for performing flexible verification and stubbing in Mockito. It extends ArgumentMatchers class to access all the matcher functions. Mockito uses equal() as a legacy method for verification and matching of argument values.
mockito. Matchers is deprecated, ArgumentMatchers should be used instead.
Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo. class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.
From the javadocs of any()
Since Mockito 2.1.0, only allow non-null
String
. As this is a nullable reference, the suggested API to matchnull
wrapper would beisNull()
. We felt this change would make tests harness much safer that it was with Mockito 1.x.
So, the way to match nullable string arguments is explicit declaration:
nullable(String.class)
I got this to work by switching to any(String.class)
I find this a bit misleading, because the API seems to suggest that anyString()
is just an alias for any(String.class)
at least up till the 2.0 update. To be fair, the documentation does specify that anyString()
only matches non-null strings. It just seems counter-intuitive to me.
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