Is it possible to use Mockito in Kotlin?

atok picture atok · May 18, 2015 · Viewed 32k times · Source

The problem I'm facing is that Matchers.anyObject() returns null. When used to mock method that only accepts non-nullable types it causes a "Should not be null" exception to be thrown.

`when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -> someResponse }

Mocked method:

public open fun login(userCredentials: UserCredentials): Response

Answer

Sergey Mashkov picture Sergey Mashkov · May 18, 2015

There are two possible workarounds:

private fun <T> anyObject(): T {
    Mockito.anyObject<T>()
    return uninitialized()
}

private fun <T> uninitialized(): T = null as T

@Test
fun myTest() {
    `when`(mockedBackend).login(anyObject())).thenAnswer { ... }
}

The other workaround is

private fun <T> anyObject(): T {
    return Mockito.anyObject<T>()
}

@Test
fun myTest() {
    `when`(mockedBackend).login(anyObject())).thenAnswer { ... }
}

Here is some more discussion on this topic, where the workaround is first suggested.