0
0
Kotlinprogramming~5 mins

Mocking with MockK in Kotlin

Choose your learning style9 modes available
Introduction

Mocking helps you test parts of your program by pretending some parts work in a certain way. MockK is a tool that makes this easy in Kotlin.

When you want to test a function but it depends on another part that is slow or complicated.
When you want to check if a function calls another function correctly.
When you want to simulate different responses from a part of your program to see how your code reacts.
When you want to isolate the code you are testing from outside effects like databases or web services.
Syntax
Kotlin
val mock = mockk<ClassName>()
every { mock.someFunction() } returns someValue
// Use mock in your tests

mockk() creates a fake version of a class or interface.

every { ... } returns ... sets what the fake should return when a function is called.

Examples
This creates a fake list and says its size is always 3.
Kotlin
val mockList = mockk<MutableList<String>>()
every { mockList.size } returns 3
This fakes a calculator's add function to return 5 when called with 2 and 3.
Kotlin
val mockCalculator = mockk<Calculator>()
every { mockCalculator.add(2, 3) } returns 5
This makes the fake service throw an error when fetchData is called.
Kotlin
val mockService = mockk<Service>()
every { mockService.fetchData() } throws RuntimeException("Error")
Sample Program

This program creates a fake Calculator. It tells the fake to return 10 when add(1, 2) is called, instead of 3. Then it prints the result.

Kotlin
import io.mockk.mockk
import io.mockk.every

class Calculator {
    fun add(a: Int, b: Int): Int = a + b
}

fun main() {
    val mockCalc = mockk<Calculator>()
    every { mockCalc.add(1, 2) } returns 10

    println(mockCalc.add(1, 2))
}
OutputSuccess
Important Notes

MockK works well with Kotlin features like coroutines and final classes.

Remember to add MockK dependencies to your project to use it.

Mocks do not run real code unless you tell them to.

Summary

Mocking lets you test code by faking parts that are hard to use in tests.

MockK is a Kotlin tool that makes mocking simple and powerful.

You create mocks, set their behavior, and then use them in your tests.