A developer testing with Mockito in Kotlin is trying to capture arguments passed to a mocked method but gets a NullPointerException. The test setup involves calling a method with multiple parameters and verifying the call using ArgumentCaptor. However, after calling verify(service, times(2)).method(argumentCaptor.capture(), argumentCaptor.capture()), the captured values return null. The issue seems related to Kotlin’s null-safety or vararg handling, as the target method signature is fun method(param1: String, vararg param2: String?). The user is unsure how to correctly capture arguments when using Mockito’s ArgumentCaptor in Kotlin.
Hey! I’ve run into this issue before. The root cause is that Mockito’s ArgumentCaptor doesn’t handle Kotlin varargs or nullable types well when you try to capture multiple parameters with the same captor. In your case, calling argumentCaptor.capture() twice for param1 and vararg param2 results in null for the captured values.
The workaround is to use separate captors for each parameter:
val param1Captor = ArgumentCaptor.forClass(String::class.java) val param2Captor = ArgumentCaptor.forClass(Array::class.java)
verify(service).method(param1Captor.capture(), *param2Captor.capture())
println(param1Captor.value) println(param2Captor.value.joinToString())
This keeps Kotlin’s null-safety and vararg semantics happy.
Yep, exactly! I hit this same problem when testing vararg methods in Kotlin. Using a single ArgumentCaptor for multiple parameters doesn’t work — the first capture is fine, but the vararg becomes null. Splitting them into two distinct captors solves the issue every time.
Also, a tip: if you want to capture multiple invocations, use verify(service, times(2)) with the separate captors and then access .allValues instead of .value. For example:
verify(service, times(2)).method(param1Captor.capture(), *param2Captor.capture()) println(param1Captor.allValues)
This way, you can inspect each call individually, which is very handy when testing Kotlin methods with varargs.