Automatically stub by relaxing

If a method has not been stubbed, MockK will throw an error if it is called. This is designed to help make your tests easier to debug, as you’ll know if you forgot to mock a method.

  1. interface Navigator {
  2. val currentLocation: String
  3. fun navigateTo(newLocation: String): Unit
  4. }
  5. val navigator = mockk<Navigator>()
  6. every { navigator.currentLocation } returns "Home"
  7. // prints "Home"
  8. println(navigator.currentLocation)
  9. // throws an error
  10. navigator.navigateTo("Store")

For more complicated objects, you can tell MockK to return simple values for all methods that have not been stubbed, rather than throwing. This is done by using the relaxed parameter when calling the mockk function.

  1. val navigator = mockk<Navigator>(relaxed = true)
  2. every { navigator.currentLocation } returns "Home"
  3. // prints "Home"
  4. println(navigator.currentLocation)
  5. // does nothing
  6. navigator.navigateTo("Store")

If desired, you can choose to only relax methods that return Unit. This lets you pre-stub methods that just trigger side-effects rather than returning a value.

  1. val navigator = mockk<Navigator>(relaxUnitFun = true)