Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a possible null parameter in Mockito

Tags:

mockito

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()); 
like image 651
GridDragon Avatar asked Oct 24 '16 18:10

GridDragon


People also ask

Does Mockito any () match null?

Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments.

What is argument matcher in Mockito?

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.

What can I use instead of Mockito matchers?

mockito. Matchers is deprecated, ArgumentMatchers should be used instead.

Can the Mockito Matcher methods be used as return values?

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.


2 Answers

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 match null wrapper would be isNull(). 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) 
like image 177
WindRider Avatar answered Sep 28 '22 07:09

WindRider


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.

like image 23
GridDragon Avatar answered Sep 28 '22 08:09

GridDragon