How to mock a function

Why mock?

  • isolate the code under test
  • test only the code under test
  • the injected dependencies are not always easy to create

The every function

Simplest example. By default mocks are strict, so you need to provide some behaviour. We do so using the every function.

val car = mockk<Car>()
 
every { car.drive(Direction.NORTH) } returns Outcome.OK
 
car.drive(Direction.NORTH) // returns OK
 
verify { car.drive(Direction.NORTH) }
 
confirmVerified(car)

Sometimes, the behaviour of the mock depends on the input. Sometimes the input can be hard to create. We can use the any() function to match any input.

val car = mockk<Car>()
 
every { car.drive(any()) } returns Outcome.OK
car.drive(Direction.NORTH) // returns OK
 
verify { car.drive(Direction.NORTH) }
 
confirmVerified(car)

The returnsArgument function

Sometimes, we want to return the input. We can use the returnsArgument function.

val car = mockk<Car>()
 
every { car.drive(any()) } returnsArgument 0
 
val result = car.drive(Direction.NORTH) // returns Direction.NORTH
 
assertEquals(Direction.NORTH, result)