When using Mockito with Kotlin how do you get around any() must not be null?

Viewed 1760

While trying to mock up a function call getInventoryList(object, string, int, object, int) I found that I would continually encounter the error ArgumentMatchers.any() must not be null.

Here are some solutions I tried. The MockitoHelper

object MockitoHelper {
fun <T> anyObject(): T {
    Mockito.any<T>()
    return uninitialized()
}
@Suppress("UNCHECKED_CAST")
   fun <T> uninitialized(): T =  null as T
}

The any object deprecated function

ArgumentMatchers.anyObject()

The any(class : T)

ArgumentMatchers.any(Object::class.java)

None of the above worked for this particular problem. Each of them came back with a similar must not be null error

2 Answers

Here is the solution to the problem. Tell Kotlin that if there is a null return to use an initialized version of the object.

ArgumentMatchers.any(Object::class.java) ?: Object()

This worked for my solution

There are a number of rough edges when using mockito with Kotlin.

This small library takes care of the major ones: https://github.com/nhaarman/mockito-kotlin

From the wiki:

Furthermore, Mockito returns null values for calls to method like any(), which can cause IllegalStateException when passing them to non-nullable parameters. This library solves that issue by trying to create actual instances to return.

This is how they implement any

inline fun <reified T : Any> any(): T {
    return Mockito.any(T::class.java) ?: createInstance()
}

createInstance() is implemented like this:

inline fun <reified T : Any> createInstance(): T {
    return when (T::class) {
        Boolean::class -> false as T
        Byte::class -> 0.toByte() as T
        Char::class -> 0.toChar() as T
        Short::class -> 0.toShort() as T
        Int::class -> 0 as T
        Long::class -> 0L as T
        Float::class -> 0f as T
        Double::class -> 0.0 as T
        else -> createInstance(T::class)
    }
}

fun <T : Any> createInstance(kClass: KClass<T>): T {
    return castNull()
}
Related