Kotlin

MockK — Kotlin-Idiomatic Mocking

admin by @admin ADMIN
10m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
MockK plays well with Kotlin: final classes, coroutines, top-level functions, all mockable. `every { ... } returns ...` is the canonical setup.
Kotlin
Raw
// build.gradle.kts:
//   testImplementation("io.mockk:mockk:1.13.+")

import io.mockk.*
import kotlinx.coroutines.test.runTest
import kotlin.test.*

interface UserRepo { suspend fun findById(id: Int): String? }

class UserService(private val repo: UserRepo) {
    suspend fun greet(id: Int): String =
        repo.findById(id)?.let { "Hello $it" } ?: "Unknown"
}

class UserServiceTest {

    @Test
    fun greets_known_user() = runTest {
        val repo = mockk<UserRepo>()
        coEvery { repo.findById(42) } returns "Alice"

        val service = UserService(repo)
        assertEquals("Hello Alice", service.greet(42))

        coVerify(exactly = 1) { repo.findById(42) }
    }

    @Test
    fun returns_unknown_when_repo_empty() = runTest {
        val repo = mockk<UserRepo>()
        coEvery { repo.findById(any()) } returns null
        assertEquals("Unknown", UserService(repo).greet(99))
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.