Mockito NullPointerException while using any

To extend on what @jeff-bowman said in his answer, any() returns null, so if you need something that doesn't return null, you can try this:

/**
 * never returns null
 */
private inline fun <reified T> any(type: Class<T>): T = Mockito.any(type)

/**
 * returns null
 */
private inline fun <reified T> any(): T = Mockito.any<T>()

As Oliver mentioned in the comments, you can't apply when to happen to all objects. Mockito works via subclassing, so you have to create a mock instance using mock, spy, or a @Mock or @Spy annotation; customize the behavior; and then install the mock using dependency injection or other similar tricks.


As to why this happens, the return value for any() actually is null; matchers like any are only supposed to be used as arguments to when and verify, and Mockito can't produce a specialized instance of Class that represents "any Class", so Mockito returns a dummy value (null) and stores data on a specialized stack of argument matchers. Though Mockito has better error messages to alert you to this situation, your code NPEs before Mockito can give you a proper exception with usage examples.

For more about matcher return values and the stack, see my other SO answer on "How do Mockito matchers work?".

Tags:

Junit4

Mockito