4

I'm using an ArgumentCaptor with @Captor annotation in Kotlin like this

@Captor private lateinit var captor: ArgumentCaptor<MyObject>
@Mock private lateinit var mockObject: InnerObject
private lateinit var objectToTest: MyClass

@Before
fun setUp() {
    MockitoAnnotations.initMocks(this)

    objectToTest = MyClass(mockObject)
}

fun testSomething() {
    objectToTest.doSomething()

    verify(mockObject).callMethod(captor.capture())
    assertThat(expectedResult, captor.value)

}

The method callMethod() is called inside doSomething() and I want to capture the parameter sent to it.

My problem is that I'm getting:

java.lang.IllegalStateException: captor.capture() must not be null

I tried the same approach using java and it's working, when I convert it to Kotlin I get the exception.

Is this related to Kotlin? Or am I not using @Captor the right way?

Janusz
  • 182,484
  • 112
  • 300
  • 368
Othmandroid
  • 175
  • 1
  • 10

2 Answers2

4

It is related to Kotlin, because all parameters and fields are not nullable by default. You have to define the parameter of callMethod nullable:

mockObject).callMethod( any : Any? )

Another way to solve it, is to use mockito-kotlin which avoids such IllegalStateException and @KCaptor annotation of mockito4kotlin.annotation:

import org.mockito4kotlin.annotation.KCaptor
import org.mockito4kotlin.annotation.MockAnnotations

@KCaptor
lateinit var captor: KArgumentCaptor<MyObject>

fun setUp() {
    MockAnnotations.initMocks(this)

    objectToTest = MyClass(mockObject)
}

fun testSomething() {

    objectToTest.doSomething()


    verify(mockObject).callMethod(captor.capture())
    assertThat(expectedResult, captor.value)

}
Willi Mentzel
  • 24,988
  • 16
  • 102
  • 110
wickie73
  • 56
  • 2
  • 2
-1

If you are using Mockito, you need to call MockitoAnnotations.initMocks(this) in test class setup method. Your captor property was never initialized, that's why you are getting IllegalStateException.

Edit: I think that you'll find a solution in this stackoverflow question. Your question might also be a duplicate question since the similar problem is stated in the link that I provided you.

TheTechWolf
  • 1,854
  • 2
  • 18
  • 24