Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get Mockito to play nice with Kotlin non-nullable types?

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?

like image 555
CaptainForge Avatar asked Nov 08 '22 03:11

CaptainForge


1 Answers

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
}
like image 178
nits Avatar answered Nov 14 '22 23:11

nits