What it is
MockK is a mocking library built for Kotlin, supporting coroutines, final classes, objects, extension functions and constructor mocking.
every { } configures behaviour, verify { } asserts calls, and coEvery/coVerify handle suspend functions. Relaxed mocks return defaults instead of throwing.
Installation
testImplementation("io.mockk:mockk:1.13.13")Getting started
The smallest useful thing you can do with it, and what each part means.
kotlin
val repo = mockk<BookRepository>()
// coEvery for suspend functions — every would not compile.
coEvery { repo.findById(42) } returns Book(42, "Dune")
coEvery { repo.findById(99) } returns null
coEvery { repo.save(any()) } throws DatabaseException()
val service = BookService(repo)
runTest {
assertEquals("Dune", service.getTitle(42))
coVerify(exactly = 1) { repo.findById(42) }
coVerify(exactly = 0) { repo.delete(any()) }
}Advanced usage
Where the library earns its place over a simpler alternative.
kotlin
// Capture an argument for detailed assertions.
val slot = slot<Book>()
coEvery { repo.save(capture(slot)) } returns true
service.create("Dune", 1965)
assertEquals(1965, slot.captured.year)
// A spy calls through to the real object except where stubbed.
val spy = spyk(RealCache())
every { spy.get("missing") } returns null
// Mock a Kotlin object (singleton) — impossible in Mockito.
mockkObject(FeatureFlags)
every { FeatureFlags.isEnabled("new-ui") } returns true
// unmockkObject(FeatureFlags) in teardown, or it leaks between testsErrors and fixes
The failures you are most likely to hit, and what actually resolves them.
- no answer found for the call
- The invocation did not match any every block. Print the actual arguments, or use relaxed = true while diagnosing.
- Tests pass alone but fail together
- A mockkObject or mockkStatic leaked. Add unmockkAll() to an @AfterEach.
Best practices
- Use coEvery and coVerify for suspend functions.
- Call unmockkAll() in teardown when using mockkObject or mockkStatic.
- Use relaxed = true sparingly; it hides calls you did not intend to allow.
- Prefer real fakes for simple interfaces — a hand-written stub is often clearer than a mock.
Background
Why it exists, and what it was reacting to.
Mockito struggles with Kotlin because classes are final by default and suspend functions are compiled unusually. MockK was written for Kotlin's semantics from the start.
