In the world of software testing, mocking is an essential technique used to simulate real objects in a controlled environment. This is particularly useful when you need to test components that interact with external systems like databases or servers. MockK is a popular library for mocking in Kotlin, allowing developers to create mocks and stubs for their unit tests.
What is Mocking?
Mocking is the process of creating a fake version of an object or system that mimics the behavior of a real object. This allows developers to test their code in isolation, without relying on external dependencies. By simulating these dependencies — for example, a connection to a database or a remote API — you can focus on testing the logic of your code rather than dealing with the complexities of external systems, and your tests run faster since they don't use the real object.
Advantages of mocking:
Isolation of code — Ensures tests aren't influenced by external dependencies, making them reliable.
Reduced complexity — Avoids complex test setups.
Control over behaviors — Precisely define mock behaviors under various conditions.
Introducing MockK
MockK is a robust and flexible mocking library tailored for Kotlin. It offers Kotlin-specific features such as handling coroutines and extension functions, and provides a concise, intuitive API. It's actively maintained and has a growing community.
Add MockK as a test dependency. If you're using a Gradle version catalog, declare the version and library in libs.versions.toml:
[versions]
mockk = "1.14.11"
[libraries]
mockk = { group = "io.mockk", name = "mockk", version.ref = "mockk" }Then reference it in your module's build.gradle.kts:
dependencies {
testImplementation(libs.mockk)
}Check Maven Central for the latest released version.
A basic MockK example
Suppose you have a WeatherService class that fetches weather data from an external API. The goal is to test WeatherService independently of its dependencies by mocking the ApiClient interface, so the test doesn't need a real network call.
// Assuming these classes are defined somewhere in your codebase
data class Weather(val condition: String, val temperature: Int)
// Interface for the API client that WeatherService depends on.
interface ApiClient {
fun fetchWeather(city: String): Weather
}
// WeatherService uses the ApiClient to fetch weather data for a given city.
class WeatherService(private val apiClient: ApiClient) {
fun getWeather(city: String): Weather {
return apiClient.fetchWeather(city)
}
}You can mock ApiClient to simulate a server response:
// Unit test for WeatherService using MockK to mock the ApiClient dependency.
class WeatherServiceTest {
private val mockApiClient = mockk<ApiClient>() // Create a mock instance of ApiClient
private val weatherService = WeatherService(mockApiClient) // Inject the mock into WeatherService
@Test
fun `test getWeather returns correct weather data`() {
// Given: set up the mock behavior and test data
val city = "New York"
val expectedWeather = Weather("Sunny", 25)
every { mockApiClient.fetchWeather(city) } returns expectedWeather
// When: call the method under test
val actualWeather = weatherService.getWeather(city)
// Then: verify the result
assertEquals(expectedWeather, actualWeather)
// Verify: ensure the interaction with the mock happened as expected
verify { mockApiClient.fetchWeather(city) }
}
}Here, mockk<ApiClient>() creates a mock instance, which is injected into the object under test. The every { } block defines the mock's behavior, the service method is called as normal, assertEquals checks the outcome, and verify { } confirms the expected interaction actually took place — so the test fails if it doesn't.
Argument matchers
Argument matchers let you set up flexible, precise conditions for your mocked methods — defining how a mock should behave for different kinds of input.
Matching specific values (
eq)
By default, MockK compares argument values using equals() (Kotlin's ==). Passing a literal value implicitly uses the eq matcher:
every { myMockObject.myMethod("foo") } returns 42
// equivalent to:
every { myMockObject.myMethod(eq("foo")) } returns 42myMockObject.myMethod returns 42 only when called with the exact string "foo".
Matching any value (
any)
any() matches any value of the expected type, regardless of content. You can freely mix literal values, eq, and any in the same call:
every { myMockObject.myMethod(any()) } returns 42Matching null values (
isNull)
isNull<T>() matches specifically when the argument is null:
every { myMockObject.myMethod(isNull<String>()) } returns 42Matching ranges (
range)
range restricts a match to a range of acceptable values:
every { myMockObject.myMethod(range(10, 20)) } returns 42myMethod returns 42 for any value between 10 and 20, inclusive.
Matching with a custom predicate (
match)
match lets you supply an arbitrary predicate lambda that the argument must satisfy. It isn't limited to collections — it works for any argument type — but it's especially handy for asserting conditions on a list or set:
every { myMockObject.myMethod(match { it.contains("foo") && it.contains("bar") }) } returns 42This returns 42 only if the method is called with a collection containing both "foo" and "bar".
Throwing exceptions
You can configure a mock to throw, letting you test your error-handling paths:
every { myMockObject.myMethod(any()) } throws RuntimeException("An error occurred")Stubbing
Unit-returning functions
For a function that returns Unit, use justRun — or any of its equivalent forms:
justRun { myMockObject.myMethod(any()) }
// Equivalent alternatives:
every { myMockObject.myMethod(any()) } just Runs
every { myMockObject.myMethod(any()) } returns Unit
every { myMockObject.myMethod(any()) } answers { Unit }Spying
Both mocks and spies are test doubles, but they serve different purposes:
Mock — Simulates an object's behavior entirely. You configure return values and verify interactions, with complete control over behavior.
Spy — Wraps a real object. It calls the actual methods by default, while still letting you verify interactions or override specific behaviors as needed.
spyk() creates a spy around a real instance:
// Class representing a weather service
class WeatherService {
fun fetchWeather(city: String): String {
// Imagine this method makes an API call to fetch weather data
return "Sunny in $city"
}
}
class WeatherServiceTest {
@Test
fun `test fetchWeather using spy`() {
// Given: create a real instance and wrap it in a spy
val realWeatherService = WeatherService()
val weatherServiceSpy = spyk(realWeatherService)
// When: call the fetchWeather method
val weather = weatherServiceSpy.fetchWeather("New York")
// Then: verify the call and assert the real result
verify { weatherServiceSpy.fetchWeather("New York") }
assertEquals("Sunny in New York", weather)
}
}The spy calls the real fetchWeather implementation while still letting you verify how it was called.
MockK annotations
MockK provides annotations that remove a lot of manual setup boilerplate:
Annotation | Purpose |
|---|---|
| Creates a mock instance of a class or interface. |
| Automatically injects the mocks (marked |
| Creates a spy on a class — a partial mock that lets you override specific methods while the rest keep their real behavior. |
@MockKand@InjectMockKs
// Assuming these classes are defined somewhere in your codebase
data class Weather(val condition: String, val temperature: Int)
interface ApiClient {
fun fetchWeather(city: String): Weather
}
class WeatherService(private val apiClient: ApiClient) {
fun getWeather(city: String): Weather {
return apiClient.fetchWeather(city)
}
}
@ExtendWith(MockKExtension::class)
class WeatherServiceTest {
@MockK // Creates a mock instance of ApiClient
private lateinit var mockApiClient: ApiClient
@InjectMockKs // Constructs WeatherService, injecting mockApiClient
private lateinit var weatherService: WeatherService
@Test
fun `test getWeather returns correct weather data`() {
val city = "New York"
val expectedWeather = Weather("Sunny", 25)
every { mockApiClient.fetchWeather(city) } returns expectedWeather
val actualWeather = weatherService.getWeather(city)
assertEquals(expectedWeather, actualWeather)
verify { mockApiClient.fetchWeather(city) }
}
}@InjectMockKs looks at the constructor (or properties) of WeatherService and wires in any matching @MockK-annotated mocks — no manual instantiation required.
@SpyK
The @SpyK annotation (note the capitalization — it's SpyK, not Spyk) does the same job as calling spyk() manually, but through annotation processing:
class WeatherService {
fun fetchWeather(city: String): String {
return "Sunny in $city"
}
}
@ExtendWith(MockKExtension::class)
class WeatherServiceTest {
@SpyK
private lateinit var weatherServiceSpy: WeatherService
@Test
fun `test fetchWeather using spy`() {
val weather = weatherServiceSpy.fetchWeather("New York")
verify { weatherServiceSpy.fetchWeather("New York") }
assertEquals("Sunny in New York", weather)
}
}Object mocking
Object mocking simulates the behavior of Kotlin objects — singletons and utility classes — so their behavior can be controlled during a test.
mockkObject(...)— Mocks a Kotlin object, letting you define its methods' behavior withevery { }.unmockkObject(...)— Removes the mock, restoring the object's real behavior. Always unmock at the end of a test to prevent leaking state into other tests.
// Define WeatherService as an object
object WeatherService {
fun fetchWeather(city: String): String {
return "Sunny in $city"
}
}
class WeatherServiceTest {
@Test
fun `test fetchWeather using mockkObject`() {
// Given: mock the WeatherService object
mockkObject(WeatherService)
every { WeatherService.fetchWeather("New York") } returns "Sunny in New York"
// When: call the fetchWeather method
val weather = WeatherService.fetchWeather("New York")
// Then: verify the interaction and the result
verify { WeatherService.fetchWeather("New York") }
assertEquals("Sunny in New York", weather)
// Finally: clear the mock so it doesn't leak into other tests
unmockkObject(WeatherService)
}
}Conclusion
MockK is a sophisticated tool for Kotlin developers, enabling efficient simulation of dependencies within unit tests. Using mocks and spies gives you precise control over your testing environment, helping you build isolated, reliable tests that measure only the code under scrutiny. The ability to define behavior, verify interactions, and simulate exceptions is essential for crafting high-quality, maintainable software — with MockK, your Kotlin applications stay robust and your test suite stays clean.