Mockito in Kotlinany()
OrisA()
When you use```java.lang.IllegalStateException: Mockito.any() must not be null
This error does not occur in Null-safe Kotlin because these methods return null (if it is a primitive type, it returns the default value, so this error does not occur).
Of course, setting the method argument to be verified to Nullable will solve the problem, but you don't want to do that.
For example, I want to mock the following part and verify the arguments.
```kotlin
transition.onNext(TransitionType.Success())
Since the actual code and the test are different instances at the time of verification, I want to verify whether they are the same class. So I write it like this.
Mockito.doNothing().`when`(mockEventBus).onNext(Mockito.isA(TransitionType.Success::class.java))
This will result in an error.
If you cast it like the following `nullReturn ()`
, it will work.
class TestUtils private constructor() {
companion object {
fun <T> isA(type: Class<T>): T {
Mockito.isA<T>(type)
return nullReturn()
}
fun <T> any(): T {
Mockito.any<T>()
return nullReturn()
}
private fun <T> nullReturn(): T = null as T
}
}
Mockito.doNothing().`when`(mockEventBus).onNext(TestUtils.isA(TransitionType.Success::class.java))
For unknown reasons, Kotlin can bypass the compiler null check by casting null, such as `` `null as String. Since I cast it to a NotNull class, is it actually judged as NotNull even if it is null? (At runtime, it will be dropped with
TypeCastException```.)
And for some reason, casting in Generics also works at runtime.
Recommended Posts