As a very basic example to reproduce this concept, I have this class:
open class Something {
fun doSomething(param: String): Boolean {
println(param)
return true
}
}
And when I try to mock it here:
class ExampleUnitTest {
@Test
fun mockito_test() {
val myMock = Mockito.mock(Something::class.java)
Mockito.`when`(myMock.doSomething(any())).thenReturn(true)
}
}
Executing this unit test gives this error:
java.lang.IllegalStateException: any() must not be null
at com.example.mockitokotlinexample.ExampleUnitTest.mockito_test(ExampleUnitTest.kt:18)
```
I could theoretically make the parameters of the methods I'm trying to mock nullable, but that defeats the purpose of kotlin. I found alternative solutions online, namely these workarounds: https://stackoverflow.com/a/30308199/2127532
But these don't make the issue go away, it seems others have commented saying they don't work on the newest versions of Kotlin. They felt hacky to begin with.
I also tried using this library: https://github.com/nhaarman/mockito-kotlin
And again I get the IllegalStateException error.
Anyone have ideas?
I have solved this issue by creating my own any()
private fun <T> any(type : Class<T>): T {
Mockito.any(type)
return null as T
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With