0

I'm trying to verify that a method is called with a given argument. That argument is a non-nullable enum type. So I get the exception eq(SomeEnum.foo) must not be null. Here is a sample what I'm trying to do:

enum class SomeEnum {
    foo, bar
}

open class MyClass {
    fun doSomething() {
        magic(SomeEnum.foo)
    }

    internal fun magic(whatever: SomeEnum) {}
}

@Test
fun mockitoBug() {
    val sut = spy(MyClass())
    sut.doSomething()
    verify(sut).magic(eq(SomeEnum.foo))
}

Capturing does not work too. What can I do or is that really a bug as I assume?

rekire
  • 47,260
  • 30
  • 167
  • 264

1 Answers1

0

Because Mockito was designed for Java, it doesn't play well with Kotlin's null checks. A good solution is to use the mockito-kotlin extensions library: https://github.com/mockito/mockito-kotlin

It includes Kotlin versions of the matchers that won't return null. Add a dependency on mockito-kotlin and just make sure to import the Kotlin versions instead of the Java ones.

Sam
  • 8,330
  • 2
  • 26
  • 51
  • `org.mockito.kotlin.eq` is the method that needs to be imported – Lesiak Oct 29 '21 at 07:49
  • Yep I'm using `mockito-kotlin` as implied by the tag and `eq` method already. When I understand the code correctly then in case of enums null will be returned and that just works for primitive types – rekire Oct 29 '21 at 09:19
  • @rekire The body of `fun eq(value: T): T` is `return ArgumentMatchers.eq(value) ?: value`. For enum, it returns the value passed in, not null. – Lesiak Oct 29 '21 at 10:27
  • Android Studio picked up the wrong `eq` method. You are right it works now – rekire Oct 29 '21 at 10:36