Skip to content

Recommended Reading

MockK Tutorial: How to Mock Kotlin and Android Code

20 Minutes

MockK Tutorial: How to Mock Kotlin and Android Code

Fix Bugs Faster! Log Collection Made Easy

Get started

There are hundreds of mocking libraries out there, but if you’re writing Kotlin code then MockK is one of the best around. It’s designed specifically for Kotlin and lets you mock practically any feature you want, without relying on real APIs or external dependencies.

MockK has been around since 2017, but if you’re new to Kotlin or mocking libraries you may not have run into it before. We’ve put together this guide to bring you up to speed, showing you how to:

  • Isolate classes from slow or unreliable dependencies.
  • Make unit tests faster and more predictable.
  • Verify important calls without over-mocking.
  • Test suspend functions and coroutine-based code.
  • Avoid brittle mocks that break during refactoring.

The examples apply to both Kotlin/JVM and Android projects. They use kotlin.test annotations and assertions, and assume import io.mockk.* in each test file.

First, what is MockK?

MockK is a mocking library specifically designed around Kotlin’s unique linguistic features, like lambdas with receivers and null safety in the type system. It creates mock objects and functions that stand in for dependencies during testing, so you can manipulate their responses.

A mock can replace any dependency that makes a test slow or unpredictable, such as:

  • Repositories. Database and persistence layers.
  • API clients. Network calls to external services.
  • Analytics services. Event tracking and reporting.
  • Storage layers. File systems, caches, preferences.
  • Notification senders. Push, email, in-app messaging.

MockK also handles Kotlin constructs that trip up other Java-oriented libraries like final classes, objects, extension functions and suspend functions.

Its core API is nice and tight: mockk, every, verify, coEvery, and coVerify . That’s it. This makes it simple and relatively easy to learn.

💡 MockK scores 82/100 on the ProDev community, scoring highly on scope and price transparency.

Data collected in November 2026

When should you use MockK?

Use MockK when a real dependency would make the test slow, unreliable, difficult to configure or dependent on an external system.

Alternatively, you can write a simple fake yourself. This works well when the fake clearly represents the dependency, but MockK becomes the better option when building and maintaining that fake creates unnecessary work.

Use a fake whenUse a MockK mock when
Dependency is simple to implementInterface is large or complex
Realistic state changes matterOne controlled response is needed
Test double can be reusedCalls or arguments must be verified
Readability is the priorityPrecise interaction testing matters

One quick note though: remember to always mock the dependency, not the class whose behaviour you are testing.

How to install MockK

The easiest way to install MockK is by adding it as a test dependency in your Gradle build file, such as build.gradle.kts. This makes MockK available when running tests.

To add MockK to your dependencies in Gradle:

dependencies {
    testImplementation("io.mockk:mockk:VERSION")
}

Android instrumented tests run on a device or emulator, so they need the artifact built against the Android runtime rather than the plain JVM one. For these tests, use the Android-specific artifact:

dependencies {
    androidTestImplementation("io.mockk:mockk-android:VERSION")
}

Note that projects still using Groovy declare the same dependency without parentheses:

dependencies {
    testImplementation "io.mockk:mockk:VERSION"
}

Replace VERSION with the latest stable MockK release compatible with your project.

How to create your first MockK test

Whatever you’re testing with MockK, it’s important to always identify what you want to test, determine the external components your code relies on and, of course, understand the unique features of the library.

Let’s suppose UserService depends on a repository and falls back when the repository fails. Here’s the example code:

data class User(
    val id: Int,
    val name: String
)

interface UserRepository {
    fun findById(id: Int): User?
}

class UserService(
    private val repository: UserRepository
) {
    fun displayName(id: Int): String {
        return try {
            repository.findById(id)?.name ?: "Unknown user"
        } catch (exception: IllegalStateException) {
            "Unavailable"
        }
    }
}

You can create a mock repository, define its response, and inject it into the service like this:

@Test
fun `returns the user display name`() {
    val repository = mockk<UserRepository>()

    every {
        repository.findById(1)
    } returns User(1, "Ada")

    val service = UserService(repository)

    val result = service.displayName(1)

    assertEquals("Ada", result)
}

Note that MockK mocks are strict by default – strictness helps expose missing setup rather than letting an unconfigured call pass silently. A call without a configured response causes the test to fail:

service.displayName(2) // fails: no answer found for findById(2)

How to stub responses with every

Stubbing defines how a mock should behave when it receives a particular call, allowing you to control dependency responses without relying on external services.

The basic pattern is:

every {
    dependency.method(arguments)
} returns value

For example:

every {
    repository.findById(1)
} returns User(1, "Ada")

Calls with other arguments stay unstubbed and may produce unexpected results or exceptions. Strict responses make tests explicit, while argument matchers can cover groups of valid inputs.

Stubbing is really a topic all of its own, so let’s take a deeper look at some of its many variables and manifestations.

Return different values

When consecutive calls should return different results (such as reading a record, updating it, then reading it again), use returnsMany . This allows you to simulate changing responses without having to create separate mocks or repeatedly redefine their behaviour.

every {
    repository.findById(1)
} returnsMany listOf(
    User(1, "Ada"),
    User(1, "Ada Lovelace")
)

The first call returns the original name. The next returns the updated one.

Sequential responses work when the changing behaviour is the point of the test. Applied elsewhere, they make the test harder to follow.

Calculate responses with answers

Use answers when the response depends on the supplied argument:

every {
    repository.findById(any())
} answers {
    val id = firstArg<Int>()
    User(id, "User $id")
}

This lets the mock generate a value dynamically:

repository.findById(42)
// User(id = 42, name = "User 42")

For most tests, returns reads more clearly. It’s best to use answers in cases where a fixed response would misrepresent the expected behaviour.

Throw exceptions

MockK allows you to simulate exceptions thrown by a dependency without having to actually cause a failure.

To do so, first use throws to simulate the failure:

every {
    repository.findById(1)
} throws IllegalStateException("Database unavailable")

Then assert the behaviour the class exposes. UserService catches the failure and returns a fallback name:

@Test
fun `falls back when the repository fails`() {
    val repository = mockk<UserRepository>()

    every {
        repository.findById(1)
    } throws IllegalStateException()

    val result = UserService(repository).displayName(1)

    assertEquals("Unavailable", result)
}

Pro tip: Assert the application’s error state or fallback wherever possible, rather than simply checking that an internal dependency threw.

Match arguments

A stub applies only when the arguments match. MockK uses exact equality unless you supply a matcher, which widens the stub to accept a range of values.

MatcherWhat it accepts
any()Any value of the expected type
eq(value)A value equal to the supplied value
isNull()A null value
ofType<T>()Any value of a particular type
match { }Values satisfying a custom condition

The following stub accepts any positive user ID:

every {
    repository.findById(match { it > 0 })
} returns User(1, "Ada")

Matchers fit arguments whose exact value is irrelevant to the behaviour under test. Exact arguments belong in stubs where the value is part of the requirement.

MockK also provides coroutine-aware matchers such as coMatch.

How to mock Unit functions

Kotlin’s Unit is a return type that represents the absence of a meaningful return value (similar to void in Java) but strict mocks still require them to be configured.

To handle the configuration, use just Runs:

every {
    analytics.track(any())
} just Runs

The same behaviour can be expressed with:

every {
    analytics.track(any())
} returns Unit

just Runs communicates the intent more clearly.

Relaxing mocks

Relaxing mocks means creating a mock that automatically provides simple default return values for functions and properties that have not been explicitly stubbed, which greatly reduces the amount of time you’ve got to spend on test setup.

In MockK, relaxUnitFun is a targeted version of relaxed mocking that allows you to relax only functions that return Kotlin’s Unit type, without relaxing all the other functions and properties of the mock.

val analytics = mockk<Analytics>(
    relaxUnitFun = true
)

Should you use relaxed mocks?

relaxUnitFun relaxes one category of function. A fully relaxed mock goes further, returning simple default values for every unstubbed call:

val repository = mockk<UserRepository>(
    relaxed = true
)

While this reduces setup, it also makes missing expectations easier to overlook.

Strict mockRelaxed mock
Unstubbed calls failUnstubbed calls return defaults
Missing setup is visibleTests require less setup
Better for important behaviourUseful for low-impact collaborators
More explicitCan hide unexpected calls

Relaxed mocks can be useful for low-impact collaborators such as logging or analytics, provided their interactions are not central to the behaviour being tested.

“[Using relaxed mocks will] allow you as a developer to focus on testing the critical parts of your code and not worry about defining every method and property of the mock object explicitly.” Understanding the Difference Between @RelaxedMockK and @MockK in Kotlin Android. Mahmoud Shehata, LinkedIn Pulse, 2023.

How to verify calls with verify

Stubbing controls what a mock returns. Verification goes the other way and checks what your code actually sent to the dependency.

@Test
fun `requests the correct user`() {
    val repository = mockk<UserRepository>()

    every {
        repository.findById(42)
    } returns User(42, "Ada")

    UserService(repository).displayName(42)

    verify {
        repository.findById(42)
    }
}

Verification is most useful when the interaction itself is the requirement. Good examples include:

  • Saving a changed record.
  • Sending an analytics event.
  • Preventing duplicate requests.
  • Triggering a notification.
  • Calling a dependency with a required value.

But be warned: Where the returned result already proves the behaviour, additional verification is more likely to bring confusion than clarity.

Verify call counts

Verifying call counts means checking how many times a particular mocked function was invoked during a test, so you can see whether an interaction has happened too frequently or not frequently enough.

  • To check frequency, use exactly, atLeast, or atMost:
verify(exactly = 1) {
    repository.findById(42)
}
verify(atMost = 1) {
    repository.findById(any())
}
  • To assert that a call never happened:
verify(exactly = 0) {
    repository.delete(any())
}

When the order in which mocked functions are called matters to your test (for example, when testing workflows or business processes) MockK allows you to use verifyOrder andverifySequence, plus verifyAll when every configured call must have happened in any order.

  • Use verifyOrder when calls must occur in a particular relative order:
verifyOrder {
    repository.save(user)
    analytics.track("user_saved")
}
  • Use verifySequence when those must be the only calls and must occur in exactly that sequence:
verifySequence {
    repository.save(user)
    analytics.track("user_saved")
}

Never forget that order verification couples the test tightly to implementation, so it belongs only in tests where the order affects behaviour.

How to capture arguments

Verification confirms that a call happened. Capture goes further and extracts the argument itself. This matters when your code builds the value internally and the test cannot reference it beforehand.

Suppose the service constructs an analytics event:

data class AnalyticsEvent(
    val name: String,
    val properties: Map<String, String> = emptyMap()
)

interface Analytics {
    fun track(event: AnalyticsEvent)
}

class RegistrationService(
    private val analytics: Analytics
) {
    fun register(email: String) {
        analytics.track(
            AnalyticsEvent("user_registered")
        )
    }
}

You can capture the event with a slot:

@Test
fun `tracks the created user`() {
    val analytics = mockk<Analytics>()
    val eventSlot = slot<AnalyticsEvent>()

    every {
        analytics.track(capture(eventSlot))
    } just Runs

    val service = RegistrationService(analytics)

    service.register("[email protected]")

    assertEquals(
        "user_registered",
        eventSlot.captured.name
    )
}

Mocking Kotlin coroutines

Coroutines are a first-order feature of Kotlin code, enabling Android developers to handle multiple tasks concurrently without making code complex or unwieldy.

MockK provides coroutine-specific versions of several stubbing, verification and argument-matching functions. These take a co prefix:

  • coEvery to stub responses.
  • coVerify to verify calls.
  • coAnswers to calculate responses.
  • coMatch to match coroutine arguments.

Remember though: If you can write the expected value in the test, be sure to use a matcher. Capture it when your code generates it, such as timestamps, identifiers, or constructed objects.

An introduction to mocking suspend functions

Suspend functions are Kotlin functions that can pause their execution without blocking the underlying thread and they’re a fundamental part of Kotlin coroutines.

Let’s specifically consider two suspend functions:

  • fetchUser() is a suspending repository function that retrieves user information.
  • loadUser() is a suspending function in the class being tested. It calls the repository and handles its response.

First, let’s imagine an asynchronous repository fetches user data:

interface RemoteUserRepository {
    suspend fun fetchUser(id: Int): User
}

The class under test catches java.io.IOException and converts repository responses into a success or error result:

sealed interface UserResult {
    data class Success(
        val user: User
    ) : UserResult

    data object Error : UserResult
}

class UserLoader(
    private val repository: RemoteUserRepository
) {
    suspend fun loadUser(id: Int): UserResult {
        return try {
            val user = repository.fetchUser(id)
            UserResult.Success(user)
        } catch (exception: IOException) {
            UserResult.Error
        }
    }
}

Stub and verify a suspend function

This part’s really simple: you can use coEvery to control the repository response and coVerify to confirm the expected call.

@Test
fun `loads the requested user`() = runTest {
    val repository = mockk<RemoteUserRepository>()

    coEvery {
        repository.fetchUser(42)
    } returns User(42, "Ada")

    val loader = UserLoader(repository)

    val result = loader.loadUser(42)

    assertEquals(
        UserResult.Success(User(42, "Ada")),
        result
    )

    coVerify(exactly = 1) {
        repository.fetchUser(42)
    }
}

Use runTest because the test calls the suspend function loadUser.

Simulate coroutine failures

You can use throws inside coEvery to reproduce failures such as network errors.

@Test
fun `returns an error when loading fails`() = runTest {
    val repository = mockk<RemoteUserRepository>()

    coEvery {
        repository.fetchUser(42)
    } throws IOException("Network unavailable")

    val loader = UserLoader(repository)

    val result = loader.loadUser(42)

    assertEquals(
        UserResult.Error,
        result
    )
}

It’s important to test the public result exposed by the class, rather than simply checking that the mocked dependency threw an exception.

Detailed dispatcher control, virtual time, and coroutine scheduling belong in a dedicated Kotlin coroutine-testing guide. MockK’s role here is controlling the dependency response.

What if your tests pass but the problem only appears on a real device?

Unit tests cannot reproduce every device, network condition, app version, or user session. That’s what our own tool, Bugfender, is here for: it captures remote logs from deployed Kotlin and Android apps so you can investigate what actually happened.

Start using Bugfender for free

How to mock Kotlin objects

Everything we’ve covered so far has assumed the dependency arrived through a constructor. The next three techniques are escape hatches for code that does not, such as singletons, static functions, and classes you cannot easily replace. Each modifies the global state, so each needs explicit cleanup.

Kotlin object declarations can be mocked with mockkObject …

object FeatureFlags {
    fun isEnabled(name: String): Boolean = false
}
@Test
fun `uses the enabled checkout flow`() {
    mockkObject(FeatureFlags)

    every {
        FeatureFlags.isEnabled("new_checkout")
    } returns true

    assertTrue(
        FeatureFlags.isEnabled("new_checkout")
    )

    unmockkObject(FeatureFlags)
}

…But remember to always restore object mocks after the test.

Scoped mocks offer another route, since MockK removes them automatically when the block finishes, but injecting a feature-flag interface is the stronger design where the codebase allows it. Globally mocked objects create hidden state and reduce test isolation.

How to mock top-level and extension functions

On the JVM, Kotlin top-level functions compile into static methods. MockK can replace them with mockkStatic.

fun currentTimestamp(): Long =
    System.currentTimeMillis()
@Test
fun `uses a fixed timestamp`() {
    mockkStatic(::currentTimestamp)

    every {
        currentTimestamp()
    } returns 1_700_000_000_000

    assertEquals(
        1_700_000_000_000,
        currentTimestamp()
    )

    unmockkStatic(::currentTimestamp)
}

MockK can also mock module-wide extension functions using static mocking, and intercept every instance of a class with mockkConstructor.

Injecting a Clock or wrapper interface means that everything stays easier to read and less tightly coupled to implementation.

How to use a MockK spy

Unlike a regular mock, which replaces an object’s behaviour with mocked behaviour, a spy wraps an existing object and delegates calls to its real implementation by default. This is useful when you want to test a real object but also need to control or inspect some of its interactions.

val calculator = spyk(Calculator())

every {
    calculator.multiply(2, 3)
} returns 100

Other methods still use the real implementation.

We’d certainly recommend using spies when you’re gradually isolating legacy code, or when replacing the whole dependency is impractical. But they mix real and mocked behaviour, which makes failures harder to interpret. A real object with mocked dependencies remains the cleaner default.

How to clean up MockK tests

Object, static, and constructor mocks modify behaviour beyond a single ordinary mock. Remove them after each test.

FunctionPurpose
clearMocks()Clears recorded calls and configured answers
unmockkObject()Restores a mocked Kotlin object
unmockkStatic()Restores static or top-level functions
unmockkAll()Removes object, static, and constructor mocks

For example:

@AfterTest
fun tearDown() {
    unmockkAll()
}

Use clearMocks() when the same mock instance is shared across tests through a setup method, since it resets recorded calls without recreating the object. The unmockk functions are particularly important here, because object, static, and constructor mocks persist beyond the test that created them.

Targeted cleanup keeps the source of global state visible. Broad cleanup is convenient, but it obscures which test introduced the mocked state.

Scoped mocking is safer when the mock is needed for only one small block.

Common MockK mistakes

When using MockK, developers often make mistakes in two key areas: they fail to grasp how mocks are configured or verified, and they stumble on Kotlin-specific features like coroutines and extension functions.

Here are some of the specific mistakes we’ve seen developers make, with some handy fixes.

MistakeFix
Mocking the class under test: This tests your setup instead of real behaviour.Mock its dependencies and keep the subject real.
Verifying every call: This couples tests to implementation details.Verify only interactions that affect the outcome.
Using relaxed mocks everywhere: default return values can hide missing stubs.Configure important behaviour explicitly.
Mocking simple values or private functions: this adds complexity and makes refactoring harder.Use real values and test public behaviour.
Overusing spies or global mocks: they introduce hidden state and brittle cleanup.Prefer dependency injection and restore object or static mocks after each test.

A good mock makes the scenario clearer. When setup outweighs the behaviour, consider a fake or a simpler design.

MockK vs Mockito for Kotlin

This article is first and foremost a tutorial, but it’s also worth a quick comparison of the MockK and Mockito libraries, as this often causes confusion. Both libraries can test Kotlin code, but their APIs and Kotlin support differ.

MockKMockito
Kotlin-focused API and DSLOriginally designed for Java, with Kotlin integrations
Dedicated coroutine DSL (coEvery, coVerify)Can mock suspend functions, but uses different APIs
Dedicated object and static mocking APIsStatic mocking is available on supported JVM configurations
Uses every and verifyUses when and verify

You should make your choice based on the project, existing test suite, and team familiarity.

MockK is often a natural choice for Kotlin-first projects, particularly when tests rely heavily on Kotlin-specific language features. Mockito can be a good fit for mixed Java/Kotlin projects, especially when the team already uses it extensively.

And finally… how to debug Kotlin production issues

MockK controls known dependencies under test conditions, but it can struggle when exposed to real-world issues: real devices, intermittent connectivity, unexpected data, timing, background execution, or app versions.

We’ve built Bugfender for just this kind of situation. Our solution captures remote logs from deployed Kotlin and Android applications, showing which scenario actually occurred on a user’s device.

For best outcomes, we’d recommend using MockK to verify expected dependency behaviour before release, then Bugfender to investigate issues that appear only in production.

Start using Bugfender for free

Frequently asked questions

What is the difference between every and verify in MockK?

every defines what a mocked function should return or throw. verify checks whether the function was called.

Use every during test setup. Add verify only when the interaction itself matters, such as saving data, sending an event, or preventing duplicate calls.

What is the difference between every and coEvery?

Use every for regular functions and coEvery for suspend functions.

The same distinction applies to verify and coVerify. Use runTest when the test executes suspend code.

What is the difference between matching and capturing arguments?

Matching decides whether a stub applies to a call, using any(), eq(), or match {}. Capturing extracts the actual argument into a slot so the test can assert on it afterwards.

Use a matcher when you already know the expected value. Use capture when your code generates the value internally.

Can MockK mock final classes?

Yes. MockK mocks final classes in regular JVM unit tests without requiring the class to be opened or extracted into an interface, which is a common friction point in Java-oriented libraries. Support inside Android instrumented tests varies by Android version and instrumentation method, as covered in the MockK Android documentation.

Should I use relaxed mocks?

Use them selectively. Relaxed mocks reduce setup by returning default values, but they can hide missing stubs and unexpected calls that a strict mock would surface immediately. Strict mocks are usually safer for repositories and other dependencies whose return values directly affect the assertion at the end of the test.

Can MockK mock private functions?

MockK supports private-function mocking, though testing observable behaviour through the public API is almost always the better approach. Private functions change frequently during refactoring, so tests bound to them break without any real regression. Complex private behaviour usually signals that the logic belongs in a separate testable class.

Does MockK work with Android?

Yes. Use the mockk artifact for local JVM unit tests and mockk-android for instrumented tests running on a device or emulator. The set of available advanced features differs depending on the Android version and the instrumentation environment, so verify support for object and static mocking in your specific setup.

Expect The Unexpected!

Debug Faster With Bugfender

Start for Free
blog author

Aleix Ventayol

Aleix Ventayol is CEO and co-founder of Bugfender, with 20 years' experience building apps and solutions for clients like AVG, Qustodio, Primavera Sound and Levi's. As a former CTO and full-stack developer, Aleix is passionate about building tools that solve the real problems of app development and help teams build better software.

Join thousands of developers
and start fixing bugs faster than ever.