Run assertions with an argument

There are some special argument matchers that can only be used when verifying that a mocked function was called. withArg and its variants allow you to capture an argument and run your own assertions on it without the need to set up a capturing slot.

  1. data class File(
  2. val name: String,
  3. val data: ByteArray
  4. )
  5. interface FileNetwork {
  6. fun download(name: String): File
  7. fun upload(file: File)
  8. }

When using a capturing slot, testing the FileNetwork.download function looks like this:

  1. val network = mockk<FileNetwork>()
  2. val slot = slot<String>()
  3. every { network.download(capture(slot)) } returns mockk()
  4. network.download("testfile")
  5. verify {
  6. network.download(any())
  7. }
  8. assertTrue("testfile" == slot.captured)

withArg simplifies this code so no slot is needed.

  1. val network = mockk<FileNetwork>()
  2. every { network.download(any()) } returns mockk()
  3. network.download("testfile")
  4. verify {
  5. network.download(withArg {
  6. assertTrue("testfile" == it)
  7. })
  8. }

Arrays and data classes

withArg can be helpful when you use arguments that aren’t easily compared, such as a data class containing arrays. The equals() function on an array works differently than on a List. Arrays are only equal if you compare with the exact same instance, while lists are equal if all of their items are equal. Since Kotlin data classes use the equals() function with each property, this array behaviour affects them.

  1. val expected = File("hello", data = "world".toByteArray())
  2. network.upload(File("hello", data = "world".toByteArray()))
  3. // fails because the Files are not equal
  4. verify {
  5. network.upload(expected)
  6. }

In your test, you can choose to compare properties individually using withArg.

  1. val expected = File("hello", data = "world".toByteArray())
  2. network.upload(File("hello", data = "world".toByteArray()))
  3. verify {
  4. network.upload(withArg {
  5. assertTrue(expected.name == it.name)
  6. assertTrue(expected.data contentEquals it.data)
  7. })
  8. }

Nullable arguments

withNullableArg is also provided by MockK when you wish to use it with a nullable argument.

Coroutines

MockK provides variants with withArg and withNullableArg that allow coroutine code to be executed. These variants are coWithArg and coWithNullableArg. If your assertions call a suspend function, these variants should be used.