Create a mock

The syntax to create a mock is very similar in Mockito and MockK. However, the behaviour is slightly different.

  1. // Mockito
  2. val mockedFile = mock(File::class.java)
  3. mockedFile.read() // does nothing
  1. // MockK
  2. val mockedFile = mockk<File>()
  3. mockedFile.read() // throws because the method was not stubbed

Mocked objects in MockK resemble Mockito’s STRICT_STUBS mode by default. If a method is not stubbed, then it will throw. This makes it easier to catch methods that are being called when you do not expect it, or when methods are being called with different arguments.

Mockito’s default lenient behaviour can be replicated with the relaxed setting. Relaxed mocks will have default stubs for all methods.

  1. // MockK
  2. val mockedFile = mockk<File>(relaxed = true)
  3. mockedFile.read() // will not throw

If desired, you can choose to only relax methods that return Unit.

  1. // MockK
  2. val mockedFile = mockk<File>(relaxUnitFun = true)
  3. mockedFile.read() // returns Unit, will not throw
  4. mockedFile.exists() // throws as the method returns Boolean