Mockito and non-null types in Kotlin

December 23rd 2022 Kotlin

The null safety feature in Kotlin is great for preventing NullPointerExceptions that are thrown at runtime. Unfortunately, it can sometimes cause problems when interacting with Java code or libraries. I recently ran into such a problem when trying to mock a dependency with Mockito.

When I ran the test, it failed with a NullPointerException:

java.lang.NullPointerException: any() must not be null

The cause was the any() argument matcher in my code to set up the method stub:

val myDependencyMock = Mockito.mock(MyDependency::class.java)
Mockito.`when`(myDependencyMock.getGreeting(any())).thenReturn("Hello, World!")

The method I was trying to stub was expecting a non-null String as an argument:

interface MyDependency {
    fun getGreeting(name: String): String
}

The exception was caused by the fact that the matcher returned null when called.

The simplest solution is to use the alternative any() function for matching arguments from Mockito-Kotlin instead. Since the function has the same name, you can leave the code as it is and just replace the Mockito import:

import org.mockito.ArgumentMatchers.any

with the one from Mockito-Kotlin:

import org.mockito.kotlin.any

This is already enough to fix the NullPointerException in the test. But while you are at it, you can also replace the original Mockito syntax for setting up mocks and stubs with a more Kotlin-friendly one:

val myDependencyMock = mock<MyDependency> {
    on { getGreeting(any()) } doReturn "Hello, World!"
}

In order for this code to compile, you need to add the following imports:

import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock

You can check the full code in my GitHub repository. The individual commits show the original code with the failed test, the fix with the alternate matcher, and the final mock setup in Kotlin syntax.

Java libraries can sometimes cause problems in Kotlin. However, you are probably not the first to have this happen. If the library is reasonably popular, it is very likely that there is already a Kotlin alternative or companion library that will help you.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License