2

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 } 

2 Answers 2

5

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(), ) 
Sign up to request clarification or add additional context in comments.

Comments

4

MockitoKotlinHelpers.kt can help you here. The capture function provides a way to call ArgumentCaptor.capture()

Example:

verify(service, times(2)).method( capture(argumentCaptor), capture(argumentCaptor)); 

2 Comments

Write that helper, same as the above link! And use it.
As extension function: "fun <T> ArgumentCaptor<T>.catch(): T = this.capture()"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.