Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito.any returns null

I am trying to mock a static method with parameters like this :

Mockito.when(StaticClass.staticMethod(Mockito.any(A.class), 
                                      Mockito.any(B.class), SomeEnum.FOO))
       .thenReturn(true);

I have added the following annotations :

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Parameterized.class)
@PrepareForTest({StaticClass.class, A.class, B.class})

But Mockito.any always returns null. Why ?

like image 272
Eko Avatar asked Nov 06 '17 14:11

Eko


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.

Does any () match null?

anyString() does not work for null #185.

What does Mockito any () return?

It returns the default value for the class so null for all objects and the default primitive value for primitive wrapper classes like Integer.

Why is mock returning NULL?

If a method return type is a custom class, a mock returns null because there is no empty value for a custom class. RETURN_MOCKS will try to return mocks if possible instead of null . Since final class cannot be mocked, null is still returned in that case.


1 Answers

Short answer: Use doReturn().when() instead of when().then()

Long answer can be found over here: How do Mockito matchers work?

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any()

NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

Side Note: This issue could also be described something like, How to use Mockito matchers on methods that have precondition checks for null parameters?

like image 189
Aaron Gehri Avatar answered Sep 21 '22 18:09

Aaron Gehri