Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 134 ยท Testing and Tooling

Test Doubles

Learn test doubles in Kotlin - dummies, stubs, fakes, spies and mocks, written by hand with interfaces and dependency injection, plus how MockK fits in. Runnable examples for every kind.

Real code talks to things: a database, an email service, the clock, a payment provider. Those things are slow, expensive, random or outside your control, so a test that uses them directly is slow and flaky. The fix is to replace them in tests with stand-ins that you control. These stand-ins are called test doubles, like a stunt double in a film.

The first half of this lesson is the design that makes doubles possible, dependency injection. The second half goes through the five kinds of doubles, each written by hand and run here, and finishes with a look at mocking libraries such as MockK. You should know the basics from testing in Kotlin and about interfaces.

The problem: hard-wired dependencies

Here is a function that cannot be tested well:

Kotlin
// read-only example: hard to test
fun greeting(): String {
    val hour = java.time.LocalTime.now().hour       // real clock, hard-wired
    return if (hour < 12) "Good morning" else "Good afternoon"
}

What does a test assert? The answer changes with the time you run it, so a test would pass in the morning and fail after lunch. The function creates its own dependency (the clock). The cure is to let the caller provide it.

Dependency injection in one idea

Dependency injection sounds grand, but it means only this: pass in what a class needs, usually through the constructor, and depend on an interface rather than a concrete class. No framework is required.

Kotlin Injecting the clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is Good morning, Good afternoon, production greeter works: true. fun interface (a functional interface) lets you write the double as a lambda: Clock { 9 }. Production passes the real clock; tests pass whatever time they want. The tested class never knew the difference.

The five kinds of test doubles

The vocabulary comes from the testing literature. You do not need to memorize it, but knowing which kind you are writing keeps your tests simple.

Kind What it does Typical use
Dummy Fills a parameter, never really used A required argument the test does not care about
Stub Returns fixed answers "The clock says 9"
Fake A working, simplified implementation An in-memory repository instead of a database
Spy A real or fake object that also records how it was used "Was an email sent?"
Mock Pre-programmed with expectations that it verifies "send() must be called exactly once with these arguments"

We will use one small system for all of them: a signup service that stores a user and sends a welcome email.

Kotlin
// the shared domain used in the next examples
data class User(val name: String, val email: String)

interface UserRepository {
    fun save(user: User)
    fun findByEmail(email: String): User?
}

interface Mailer {
    fun send(to: String, subject: String)
}

A missing member is a compile error

Interfaces give you a free safety net: if you forget to implement something, the code does not compile. Here a double forgets a method:

Kotlin An incomplete double (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports main.kt:5:1: error: class 'BrokenMailer' is not abstract and does not implement abstract member: followed by fun send(to: String, subject: String): Unit. (If you add override fun send(to: String, subject: String) {} to the class, the program compiles and does nothing, which is exactly a dummy.) This is one reason interface-based doubles are safer than "magic" doubles: when the interface grows, every double fails to compile until you update it.

Fakes: a simple working version

A fake really works, but takes a shortcut that makes it unfit for production. An in-memory repository backed by a MutableMap behaves like a database for the purposes of the test, and needs no setup.

Kotlin A fake repository and a service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is first: User(name=Ada, [email protected]), second: email already registered: [email protected] and users stored: 1. The fake stores state between calls, so you can test a sequence ("register twice, the second must fail"), which a stub with fixed answers cannot do. Because it behaves like the real thing, tests written against the fake keep working when you swap it for another implementation. Fakes are the most valuable doubles for core logic; write one per important dependency and reuse it across tests.

Stubs and spies: control the input, observe the output

Next, add the mailer. A spy records what was sent, so the test can ask afterwards. A stub that throws lets you test the failure path, which is almost impossible with a real mail server.

Kotlin A spy and a failing stub

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line is sent: true, messages: [([email protected], Welcome, Grace!)] and the second sent: false (the failure was handled). The spy turns an invisible side effect (an email leaving the system) into data you can assert on. The failing stub proves the error path works without a real outage.

Prefer asserting on results and state (what the function returned, what the fake contains) over asserting on calls (which method was called how many times). Call-based tests are tied to the implementation: if you refactor but the behavior stays the same, they break. Use call verification only for side effects that leave your system, like sending an email.

Mocks: expectations built in

A mock is a double that knows what calls it should receive, and complains if reality differs. Libraries make mocks by generating the implementation at run time. We can see how with the JDK's own java.lang.reflect.Proxy, which creates an implementation of an interface and sends every call to one handler. (It does not need kotlin-reflect, so it runs here.)

Kotlin A tiny mock built on Proxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program prints [send([email protected], Hi), send([email protected], Hello)], then verification passed, then Expected call <send([email protected], Hey)>, recorded calls: [send([email protected], Hi), send([email protected], Hello)]. A real mocking library adds a nice syntax, argument matchers, stubbed return values, and clear error messages, but this is the core: generate an implementation, record the calls, check them.

MockK in a real project

For Kotlin, the standard mocking library is MockK. It understands Kotlin features that Java libraries struggle with: final classes (all Kotlin classes are final by default), suspend functions, extension functions and objects. This is a read-only example; MockK is a third-party dependency (testImplementation("io.mockk:mockk:<version>")) that is not available on this site's runner.

Kotlin
// read-only example: needs the MockK dependency
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlin.test.Test
import kotlin.test.assertTrue

class WelcomeServiceTest {
    @Test
    fun sendsWelcomeMail() {
        val mailer = mockk<Mailer>(relaxed = true)       // relaxed: unstubbed calls return defaults
        val service = WelcomeService(mailer)

        val sent = service.welcome(User("Grace", "[email protected]"))

        assertTrue(sent)
        verify(exactly = 1) { mailer.send("[email protected]", "Welcome, Grace!") }
    }

    @Test
    fun survivesMailFailure() {
        val mailer = mockk<Mailer>()
        every { mailer.send(any(), any()) } throws java.io.IOException("down")

        val sent = WelcomeService(mailer).welcome(User("Linus", "[email protected]"))

        assertTrue(!sent)
    }
}

mockk<Mailer>() creates the mock. every { ... } returns/throws ... stubs an answer, and verify { ... } asserts a call happened. any() matches any argument. Using the library is fast to write, and the price is coupling to implementation details.

Choosing a double

  • Start with fakes for stateful collaborators (repositories, caches) and stubs for simple inputs (clock, random, configuration).
  • Use a spy or mock only for outgoing side effects: emails, events, payments.
  • Do not mock what you do not own (a library class with many methods); wrap it in your own small interface and mock that.
  • Do not mock value objects or simple data classes. Create real ones.
  • If a test needs many mocks, the class under test probably has too many dependencies. Treat that as a design smell.
  • Test the real integration once, too: a few integration tests with the real database catch what the doubles hide.

Common mistakes

  • Mocking everything. A test where each line sets up a mock verifies your mocks, not your code.
  • Doubles that lie. A fake that behaves differently from the real implementation (for example, ignores uniqueness constraints) gives false confidence.
  • Verifying call order and counts when the behavior does not depend on them.
  • Hard-coded Dispatchers.IO or LocalDate.now() inside a class. Inject them, as shown in testing coroutines.
  • Forgetting that Kotlin classes are final. Libraries based on subclassing cannot mock them; interfaces avoid the problem (MockK works either way).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is dependency injection, in its simplest form?

    Constructor injection plus an interface is all it takes; it lets tests substitute doubles.
  2. 2. Which test double is a working, simplified implementation such as an in-memory repository?

    A fake really works, but cheaply: in-memory storage instead of a real database.
  3. 3. You want to test that signup still succeeds when the mail server is down. Which double fits best?

    A stub that throws reproduces the failure on demand, which a real server cannot do reliably.
  4. 4. Why is it risky to assert on the exact calls made to a collaborator in every test?

    Call-based assertions are coupled to the implementation. Prefer asserting on results and state, and verify calls only for outgoing side effects.
  5. 5. Why does MockK exist when Java mocking libraries are available?

    Kotlin classes are final by default and suspend functions need special handling; MockK is designed for these.

Summary

  • Test doubles replace slow, random or external dependencies so tests are fast and deterministic.
  • Make code testable with dependency injection: depend on interfaces and pass them in through the constructor; fun interface lets a lambda act as the double.
  • The kinds: dummy (filler), stub (fixed answers), fake (simple working version), spy (records use), mock (verifies expectations).
  • Prefer fakes and stubs, assert on results and state, and verify calls only for outgoing side effects.
  • MockK is the usual Kotlin mocking library; it is read-only on this site, and hand-written doubles go a long way.
  • Do not mock what you do not own or simple values, and keep a few real integration tests.

Next: Gradle Basics for Kotlin