argThat

The argThat argument matcher in Mockito lets you create advanced argument matchers that run a function on passed arguments, and checks if the function returns true.

If you have a complicated class that can’t be easily checked using .equals(), a custom matcher can be a useful tool.

  1. `when`(
  2. mockedCar.drive(argThat { engine -> engine.dieselEngine })
  3. ).thenReturn(true)

MockK has a similar argument matcher called match. Just like argThat, you can pass a lambda in that returns a boolean.

  1. every {
  2. mockedCar.drive(match { engine -> engine.dieselEngine })
  3. } returns true

MockK also lets you use coroutines with match. Just replace the function with coMatch, then pass a suspend function lambda in. See Coroutines and suspend functions for more details.