verify

Verifying that a method was called has similar syntax in Mockito and MockK. MockK uses inline functions and keyword arguments in place of Mockito’s verification modes.

  1. // Mockito
  2. val mockedFile = mock(File::class.java)
  3. mockedFile.read()
  4. verify(mockedFile).read()
  1. // MockK
  2. val mockedFile = mockk<File>()
  3. mockedFile.read()
  4. verify { mockedFile.read() }

Verification Mode

Mockito lets extra arguments such as never() be passed to verify in the second parameter, all of which implement a VerificationMode interface. MockK has equivalents for these modes as keyword arguments in verify.

never

  1. // Mockito
  2. verify(mockedFile, never()).write()
  1. // MockK
  2. verify(inverse = true) { mockedFile.write() }

atLeast/atLeastOnce

  1. // Mockito
  2. verify(mockedFile, atLeast(3)).read()
  3. verify(mockedFile, atLeastOnce()).write()
  1. // MockK
  2. verify(atLeast = 3) { mockedFile.read() }
  3. verify(atLeast = 1) { mockedFile.write() }

atMost/atMostOnce

  1. // Mockito
  2. verify(mockedFile, atMost(3)).read()
  3. verify(mockedFile, atMostOnce()).write()
  1. // MockK
  2. verify(atMost = 3) { mockedFile.read() }
  3. verify(atMost = 1) { mockedFile.write() }

times

  1. // Mockito
  2. verify(mockedFile, times(3)).read()
  1. // MockK
  2. verify(exactly = 3) { mockedFile.read() }

timeout

  1. // Mockito
  2. verify(mockedFile, timeout(100)).readAsync()
  1. // MockK
  2. verify(timeout = 100) { mockedFile.readAsync() }

verifyNoInteractions

  1. // Mockito
  2. verifyNoInteractions(mockOne)
  3. verifyNoInteractions(mockTwo, mockThree)
  1. // MockK
  2. verify { mockOne wasNot Called }
  3. verify { listOf(mockTwo, mockThree) wasNot Called }

verifyNoMoreInteractions

  1. // Mockito
  2. verifyNoMoreInteractions(mockOne, mockTwo)
  1. // MockK
  2. confirmVerified(mockOne, mockTwo)

Coroutines

As MockK uses function literals to create stubs, small changes are needed to verify suspend functions. MockK provides functions prefixed with co as equivalents to other functions, such as coVerify. See Coroutines and suspend functions for more details.

  1. val mockedFile = mockk<File>()
  2. coVerify { mockedFile.readAsync() }