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.

// Mockito
val mockedFile = mock(File::class.java)

mockedFile.read()
verify(mockedFile).read()
// MockK
val mockedFile = mockk<File>()

mockedFile.read()
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 #

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

atLeast/atLeastOnce #

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

atMost/atMostOnce #

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

times #

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

timeout #

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

verifyNoInteractions #

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

verifyNoMoreInteractions #

// Mockito
verifyNoMoreInteractions(mockOne, mockTwo)
// MockK
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.

val mockedFile = mockk<File>()

coVerify { mockedFile.readAsync() }
Buy Me a Coffee at ko-fi.com