Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin using ArgumentCaptor.capture() returns null

I'm pretty new to testing so I might be doing something wrong.I'm trying to capture the values that are passed to a method

    @Mock
    private lateinit var service: TestService


    @InjectMocks
    private lateinit var underTest: UnderTestService

    @org.junit.jupiter.api.Test
        fun `testMethod`() {
            //given
            val var1 = Test.Value
            val var2 = TestClass::class.java
            val var3 = listOf(Entry1(), Entry2())
    
            //when
            underTest.method(var1, var2, var3)
    
            val argumentCaptor = ArgumentCaptor.forClass(String::class.java)
    
            verify(service, times(2)).method(
                argumentCaptor.capture(),
                argumentCaptor.capture()

        )

Here, after doing verify the argumentCaptor.capture() return null for some reason and I don't understand what am I doing wrong?

java.lang.NullPointerException: argumentCaptor.capture() must not be null

I think that it is kotlin related, the signature of the method that I'm trying to get the parameters looks like this

    fun method(param1: String, vararg param2: String?) {
            //do something
  }
like image 406
Truica Sorin Avatar asked May 31 '26 15:05

Truica Sorin


1 Answers

Using Mockito-Kotlin (an official Mockito library) can solve this for you.

It adds some syntactic sugar on top of Mockito. For example, a function whenever that is basically an alias for when, so that you don't need to use `when` with back-ticks.

It also has a method argumentCaptor() which creates an argument captor that does not have the NullPointerException issue. Example usage:

val argumentCaptor = argumentCaptor<String>()

verify(service, times(2)).method(
    argumentCaptor.capture(),
    argumentCaptor.capture(),
)
like image 80
tjalling Avatar answered Jun 04 '26 12:06

tjalling