0
0
Android Kotlinmobile~7 mins

MockK for mocking in Android Kotlin

Choose your learning style9 modes available
Introduction

MockK helps you test your Android app by pretending parts of your code work a certain way. This way, you can check if your app behaves correctly without needing everything to be ready.

When you want to test a function that depends on another class without running the real code.
When you want to check if a method was called during a test.
When you want to simulate different responses from a service or database.
When you want to isolate a part of your app to find bugs easily.
When you want to speed up tests by skipping slow or complex operations.
Syntax
Android Kotlin
val mockObject = mockk<ClassName>()
every { mockObject.someMethod() } returns someValue
verify { mockObject.someMethod() }

mockk() creates a fake version of a class.

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

verify { ... } checks if a method was called during the test.

Examples
This creates a fake list and tells it to say its size is 3.
Android Kotlin
val mockList = mockk<MutableList<String>>()
every { mockList.size } returns 3
This fakes a service that returns "Hello" when getData() is called.
Android Kotlin
val mockService = mockk<Service>()
every { mockService.getData() } returns "Hello"
This checks if getData() was called on the fake service.
Android Kotlin
verify { mockService.getData() }
Sample App

This code creates a fake Calculator. It tells the fake to return 10 when add(2, 3) is called. Then it calls add(2, 3) and prints the result. Finally, it checks if add(2, 3) was called.

Android Kotlin
import io.mockk.mockk
import io.mockk.every
import io.mockk.verify

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

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

  val result = mockCalc.add(2, 3)
  println("Result: $result")

  verify { mockCalc.add(2, 3) }
}
OutputSuccess
Important Notes

MockK works well with Kotlin and supports many features like spying and relaxed mocks.

Always verify important calls to make sure your code behaves as expected.

Use relaxed mocks if you want default values without specifying every behavior.

Summary

MockK creates fake objects to help test parts of your app separately.

You can tell fakes what to return and check if methods were called.

This makes testing easier, faster, and more reliable.