← Back to Kotlin Course | Chapter 13: Error Handling & Testing | Lesson 6 of 6

Mocking Basics

Mocking means building a pretend stand-in for a real, complicated piece of code, so a test can focus on just the part it actually cares about.

Creating a Mock

A mocking library like MockK can generate a fake implementation of an interface or class at test time, letting you control exactly how it behaves without needing a real implementation.

Warning: This example uses a third-party testing/mocking library that is not part of the plain Kotlin standard library and must be added as a project dependency (e.g. via Gradle) -- it cannot run in a plain kotlinc sandbox with no dependencies.

Example: Creating a Mock

markup
import io.mockk.mockk
import io.mockk.every

interface UserRepository {
    fun findName(id: Int): String
}

fun main() {
    val repo = mockk<UserRepository>()
    every { repo.findName(1) } returns "Ana"
    println(repo.findName(1))
}

Stubbing Behavior with every

every { mock.method(args) } returns value configures exactly what a mock should return for a specific call, letting a test simulate any scenario, including edge cases hard to trigger with a real implementation.

Warning: This example uses a third-party testing/mocking library that is not part of the plain Kotlin standard library and must be added as a project dependency (e.g. via Gradle) -- it cannot run in a plain kotlinc sandbox with no dependencies.

Example: Stubbing Behavior with every

markup
import io.mockk.mockk
import io.mockk.every

interface PaymentGateway {
    fun charge(amount: Double): Boolean
}

fun main() {
    val gateway = mockk<PaymentGateway>()
    every { gateway.charge(100.0) } returns false
    println("Charge succeeded: ${gateway.charge(100.0)}")
}

Verifying Interactions

verify { mock.method(args) } checks that a mock was actually called in the expected way during a test, useful for confirming side-effecting behavior rather than just a return value.

Warning: This example uses a third-party testing/mocking library that is not part of the plain Kotlin standard library and must be added as a project dependency (e.g. via Gradle) -- it cannot run in a plain kotlinc sandbox with no dependencies.

Example: Verifying Interactions

markup
import io.mockk.mockk
import io.mockk.verify
import io.mockk.every

interface Logger {
    fun log(message: String)
}

fun main() {
    val logger = mockk<Logger>(relaxed = true)
    logger.log("Application started")
    verify { logger.log("Application started") }
}

Mocking in a Test Context

Mocks are typically used inside a JUnit or Kotest test to isolate the code under test from its real dependencies, such as a database or network client, that would otherwise make the test slow or unreliable.

Warning: This example uses a third-party testing/mocking library that is not part of the plain Kotlin standard library and must be added as a project dependency (e.g. via Gradle) -- it cannot run in a plain kotlinc sandbox with no dependencies.

Example: Mocking in a Test Context

markup
import io.mockk.mockk
import io.mockk.every
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals

interface UserRepository {
    fun findName(id: Int): String
}

class GreetingServiceTest {
    @Test
    fun `greets user found in repository`() {
        val repo = mockk<UserRepository>()
        every { repo.findName(1) } returns "Ana"
        val greeting = "Hello, ${repo.findName(1)}!"
        assertEquals("Hello, Ana!", greeting)
    }
}
Common Mistakes
  1. Mocking a type that has no real behavioral seam (like a plain data class), when a real instance would be simpler and more meaningful to test with.
  2. Forgetting to stub a mock's method behavior before calling it, resulting in a default (often unhelpful) return value in the test.
  3. Over-mocking so heavily that the test verifies the mock's own configured behavior rather than anything meaningful about the real code under test.
Chapter Summary
  • Mocking creates a fake stand-in implementation of a dependency, letting tests control its behavior precisely.
  • MockK is a popular Kotlin-first mocking library, commonly used alongside JUnit or Kotest.
  • every { mock.method() } returns value stubs a mock's behavior for a specific call.
  • verify { mock.method() } checks that a particular interaction with the mock actually happened during the test.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.