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.
Mocking with MockK in 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.
val mockList = mockk<MutableList<String>>() every { mockList.size } returns 3
val mockCalculator = mockk<Calculator>() every { mockCalculator.add(2, 3) } returns 5
val mockService = mockk<Service>() every { mockService.fetchData() } throws RuntimeException("Error")
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.
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)) }
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.
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.
Practice
Solution
Step 1: Understand mocking concept
Mocking means creating fake versions of objects to test code without using real dependencies.Step 2: Identify MockK's role
MockK is a Kotlin library that helps create these fake objects easily for testing purposes.Final Answer:
To create fake objects that simulate real ones for testing -> Option AQuick Check:
MockK = mocking tool for fake objects [OK]
- Confusing MockK with build or deployment tools
- Thinking MockK is for UI design
- Assuming MockK speeds up compilation
MyService using MockK?Solution
Step 1: Recall MockK syntax for mocking
MockK uses the functionmockk<ClassName>()to create mocks.Step 2: Check each option
val mock = mockk<MyService>() usesmockk<MyService>(), which is correct syntax. Others are invalid or not MockK functions.Final Answer:
val mock = mockk<MyService>() -> Option CQuick Check:
mockk<Class>() creates mock [OK]
- Using uppercase 'MockK' as a function
- Trying to use 'new' keyword in Kotlin
- Using non-existent functions like createMock
val mock = mockk<Calculator>()
every { mock.add(2, 3) } returns 10
println(mock.add(2, 3))
println(mock.add(1, 1))Solution
Step 1: Understand mocking behavior setup
The mock is told to return 10 whenadd(2, 3)is called.Step 2: Check calls and outputs
Callingmock.add(2, 3)returns 10 as set. Callingmock.add(1, 1)has no behavior defined, so MockK throws an exception by default.Final Answer:
10 Exception -> Option AQuick Check:
Defined call returns 10; undefined call throws exception [OK]
- Assuming undefined calls return 0 or null
- Thinking all calls return the same mocked value
- Ignoring that MockK throws exceptions on undefined calls
val mock = mockk<UserRepository>()
every { mock.getUser(any()) } returns User("Alice")
mock.getUser(1)
verify { mock.getUser(1) }Solution
Step 1: Analyze mocking and stubbing
The mock is created normally, andeverysets behavior for any argument usingany(), which is valid.Step 2: Check verification usage
After callingmock.getUser(1), theverifyblock correctly checks that the method was called with argument 1.Final Answer:
No error; code is correct -> Option BQuick Check:
any() matcher and verify block used correctly [OK]
- Thinking relaxed=true is always required
- Confusing verify usage with unnecessary calls
- Misusing any() matcher outside stubbing
PaymentProcessor so that calling process(amount) returns "Success" only when amount is greater than 100, otherwise throws an exception. Which MockK setup achieves this?Solution
Step 1: Understand conditional mocking with matchers
MockK supports argument matchers likegt()(greater than) andltEq()(less than or equal) for conditions.Step 2: Evaluate options for correct matcher usage
every { mock.process(gt(100)) } returns "Success" every { mock.process(ltEq(100)) } throws IllegalArgumentException() correctly usesgt(100)to return "Success" andltEq(100)to throw exception, matching the requirement precisely.Final Answer:
every { mock.process(gt(100)) } returns "Success" every { mock.process(ltEq(100)) } throws IllegalArgumentException() -> Option DQuick Check:
Use gt() and ltEq() for conditional mocking [OK]
- Using match { } lambda instead of built-in matchers
- Mocking only specific values, missing ranges
- Returning success for all inputs ignoring conditions
Ready to prove it?
Pass the test and this pattern moves unknown
