Mocks and test doubles
suggest changeTest doubles isolate units under test from external dependencies like databases, third-party HTTP APIs, and asynchronous message brokers. In Kotlin, all classes and member methods are final by default, which poses challenges for traditional Java mocking tools.
To provide idiomatic, type-safe testing, the Kotlin ecosystem primarily relies on MockK alongside in-memory Fakes.
Test Double Terminology
- Dummy: Passed as an argument to satisfy parameter lists but never actually inspected or called.
- Stub: Provides predetermined return values to method invocations during test execution.
- Spy: Wraps a real object to record invocations while executing real implementations unless stubbed.
- Mock: Expects and verifies specific interactions (call count, arguments, execution order).
- Fake: A lightweight, working in-memory implementation of an interface (e.g.
InMemoryUserRepository).
Using MockK
MockK is built from the ground up for Kotlin, offering native support for final classes, extension functions, coroutines (suspend), and singleton object declarations.
Adding Dependency
// build.gradle.kts
dependencies {
testImplementation("io.mockk:mockk:1.14.11")
testImplementation("org.junit.jupiter:junit-jupiter:6.1.3")
}
Basic Mocking and Stubbing
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
data class User(val id: Long, val name: String, val email: String)
interface UserRepository {
fun findById(id: Long): User?
fun save(user: User): User
}
class UserService(private val repo: UserRepository) {
fun registerUser(id: Long, name: String, email: String): User {
val existing = repo.findById(id)
if (existing != null) throw IllegalArgumentException("User $id already exists")
return repo.save(User(id, name, email))
}
}
class UserServiceTest {
@Test
fun `should save user when id does not exist`() {
// Create mock
val repo = mockk<UserRepository>()
// Stub findById to return null
every { repo.findById(101L) } returns null
// Stub save to return the saved entity
every { repo.save(any()) } answers { firstArg() }
val service = UserService(repo)
val result = service.registerUser(101L, "Alice", "alice@example.com")
assertEquals("Alice", result.name)
// Verify interactions
verify(exactly = 1) { repo.findById(101L) }
verify(exactly = 1) { repo.save(match { it.email == "alice@example.com" }) }
}
}
Mocking Coroutines (suspend functions)
Standard mocking tools struggle with coroutines due to hidden Continuation parameters. MockK provides coEvery and coVerify:
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
interface PaymentGateway {
suspend fun charge(cardToken: String, amountCents: Long): Boolean
}
class OrderProcessor(private val gateway: PaymentGateway) {
suspend fun checkout(token: String, amount: Long): Boolean {
return gateway.charge(token, amount)
}
}
class OrderProcessorTest {
@Test
fun `should invoke payment gateway charge coroutine`() = runBlocking {
val gateway = mockk<PaymentGateway>()
coEvery { gateway.charge("tok_visa_123", 5000L) } returns true
val processor = OrderProcessor(gateway)
val success = processor.checkout("tok_visa_123", 5000L)
assert(success)
coVerify(exactly = 1) { gateway.charge("tok_visa_123", 5000L) }
}
}
Relaxed Mocks and Spies
Relaxed Mocks
A relaxed mock returns default values (e.g. 0, false, "", or empty collections) for unstubbed methods without throwing a MockKException:
val logger = mockk<Logger>(relaxed = true)
logger.info("Test event") // Does not throw unstubbed error
Spying on Real Objects
A spy executes the real class logic unless a specific method is stubbed:
import io.mockk.spyk
import io.mockk.every
open class TaxCalculator {
open fun calculateBaseTax(amount: Double): Double = amount * 0.10
open fun applyLuxurySurcharge(tax: Double): Double = tax + 15.0
}
fun main() {
val realCalc = TaxCalculator()
val spyCalc = spyk(realCalc)
// Override only calculateBaseTax; applyLuxurySurcharge runs real logic
every { spyCalc.calculateBaseTax(any()) } returns 5.0
val total = spyCalc.applyLuxurySurcharge(spyCalc.calculateBaseTax(100.0))
println("Calculated: $total") // 20.0 (5.0 + 15.0)
}
Hand-Written In-Memory Fakes
For core architectural contracts (such as database repositories or caches), hand-written in-memory Fakes are frequently faster, less brittle, and more readable than complex mock configurations:
class FakeUserRepository : UserRepository {
private val memoryStore = mutableMapOf<Long, User>()
override fun findById(id: Long): User? = memoryStore[id]
override fun save(user: User): User {
memoryStore[user.id] = user
return user
}
}
// In test:
val fakeRepo = FakeUserRepository()
val service = UserService(fakeRepo)
// Test against clean, authentic state logic without mock setup boilerplate
Best Practices
- Prefer Fakes over Mocks for stateful repositories: In-memory hash map fakes verify behavior and state transitions without brittle
verify()assertions. - Use MockK for Kotlin coroutines: Leverage
coEveryandcoVerifyfor suspendable functions and reactive flows. - Avoid over-mocking internal implementation details: Stub inputs and verify public outputs rather than asserting every intermediate method invocation.