Kotlin
MockK
Learn mocking with MockK.
MockK: Mocking library
MockK is a mocking library for Kotlin. It mimics the behavior of dependencies during tests; so you can write tests without real database or network calls. mockk<T>() creates a mock object, every { } defines behavior, verify { } checks calls.
val service = mockk<WeatherService>()
every { service.temperature(any()) } returns 20
verify { service.temperature("Istanbul") }
Here WeatherService is mocked; calling temperature always returns 20. verify checks that the method was called with the specified argument. MockK also supports Kotlin's suspend and extension functions; this makes it a common choice in Kotlin.
The fake pattern
Before using MockK, the fake pattern is useful to understand mocking. A fake is a hand-written class that implements an interface and offers predictable behavior in tests. It shows explicitly what MockK does behind the scenes.
interface Greeter {
fun greet(name: String): String
}
class FakeGreeter : Greeter {
override fun greet(name: String) = "Hello, $name!"
}
Here FakeGreeter implements the Greeter interface and always returns a fixed result. The test uses this fake; it does not depend on a real resource. MockK produces this fake automatically; mockk creates a mock for any interface.
Exercise Apply the fake service pattern
Define interface WeatherService; inside it add fun temperature(place: String): Int. Define class FakeWeatherService : WeatherService whose temperature always returns 20. Define class WeatherApp(private val service: WeatherService) whose fun report(place: String): String body returns "$place: ${service.temperature(place)}C". In main create val app = WeatherApp(FakeWeatherService()); print println(app.report("Istanbul")).
Show example solution
interface WeatherService {
fun temperature(place: String): Int
}
class FakeWeatherService : WeatherService {
override fun temperature(place: String): Int = 20
}
class WeatherApp(private val service: WeatherService) {
fun report(place: String): String = "$place: ${service.temperature(place)}C"
}
fun main() {
val app = WeatherApp(FakeWeatherService())
println(app.report("Istanbul"))
}
Test yourself
-
What is MockK used for?
- Mocking dependencies in tests
- Drawing interfaces
- Querying databases
- Compressing files
Show answer
Mocking dependencies in tests — MockK mimics the behavior of dependencies during tests.
-
Create a mock object
val service = ____<WeatherService>()
Show answer
val service = mockk<WeatherService>()
-
Match the MockK functions
- mockk<T>()
- Create a mock
- every { }
- Define behavior
- verify { }
- Check a call
- returns
- Return value
Next lesson: Summary - Testing