5

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?

CaptainForge
  • 1,365
  • 7
  • 21
  • 46
  • What's the behavior if you use `any(Class)` or `anyString()` instead? The [documentation](https://static.javadoc.io/org.mockito/mockito-core/2.7.9/org/mockito/ArgumentMatchers.html) says `any()` matches nulls, too. – TheOperator Aug 16 '18 at 07:04
  • I still get the same issue. The fact that `any()` matches nulls is the issue, because `any()` is returning null, and we're passing it to a method that whose parametr is non-nullable. – CaptainForge Aug 16 '18 at 15:12
  • But isn't that exactly what `any(Class)` and `anyString()` promise? They should not return nulls. – TheOperator Aug 16 '18 at 16:16
  • 1
    Try to give a shot to [MockK](https://github.com/mockk/mockk). I'm using it since months, until now had no issue. – DVarga Aug 16 '18 at 17:48
  • Did you try using the helpers in the SO post you linked, particularly `fun any(): T = Mockito.any()` ? This is from the [Android Architecture Blueprints](https://github.com/googlesamples/android-architecture/blob/todo-mvp-kotlin/todoapp/app/src/test/java/com/example/android/architecture/blueprints/todoapp/MockitoKotlinHelpers.kt) and it works for me. – Tohu Aug 17 '18 at 02:58
  • This issue is discussed here: https://github.com/mockito/mockito/issues/1255 but there is no resolution yet within Mockito. – ThomasW Mar 11 '20 at 01:52

1 Answers1

2

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
}
Boken
  • 4,825
  • 10
  • 32
  • 42
nits
  • 43
  • 11