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.
MockK for mocking in 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.
val mockList = mockk<MutableList<String>>()
every { mockList.size } returns 3val mockService = mockk<Service>()
every { mockService.getData() } returns "Hello"verify { mockService.getData() }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.
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) } }
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.
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.