iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌊

How to Capture Arguments in MockK

に公開

For example, suppose you have the following code:

fun example(flg: Boolean){
  val arg = if(flg) "true" else "false"
  mockObj.call(arg)
}

If you were to write a test, I think you would check whether the argument passed to call() contains the correct value depending on flg. (This is just an example and isn't meant to be particularly important, so it's a bit casual.)

This post is about how to verify that using MockK.

In the case of Mockito

With Mockito, the solution of using ArgumentCaptor comes up immediately.
I won't provide an explanation for this since it's not the main topic.

In the case of MockK

You can use CapturingSlot.
In this case:

@Test
fun exampleTest_true(){
  val argSlot = slot<String>()
  every{ mockObj.call(capture(argSlot) } returns Unit
  
  subject.example(true)
  
  assertEquals("true", argSlot.captured)
}

You can verify the value passed as an argument like this.

Conclusion

I wrote this post because while the solution for Mockito was easy to find, the method for MockK didn't come up as readily in comparison.

The article I referred to is below:
https://notwoods.github.io/mockk-guidebook/docs/mockito-migrate/argument-captor/

Discussion