Consider the following Kotlin code using MockK. What will be printed?
import io.mockk.mockk import io.mockk.verify class Calculator { fun add(a: Int, b: Int): Int = a + b } fun main() { val calc = mockk<Calculator>(relaxed = true) calc.add(2, 3) verify { calc.add(2, 3) } println("Verification passed") }
Think about what relaxed = true means for the mock.
Because the mock is relaxed, calling add(2, 3) does not throw an error and the call is recorded. The verify confirms the call happened, so "Verification passed" is printed.
What error will this code produce?
import io.mockk.mockk import io.mockk.verify class Service { fun fetchData(): String = "data" } fun main() { val service = mockk<Service>() verify { service.fetchData() } }
What happens if you verify a call that was never made?
Since fetchData() was never called on the mock, verify throws a MockKException indicating no calls found.
Look at this Kotlin code snippet. The stub is supposed to return 10 when compute() is called, but it returns 0 instead. Why?
import io.mockk.mockk import io.mockk.every class Processor { fun compute(): Int = 5 } fun main() { val processor = mockk<Processor>() every { processor.compute() } returns 10 println(processor.compute()) }
Consider Kotlin's default behavior for functions and MockK's handling of final methods.
By default, Kotlin functions are final. MockK cannot mock final methods unless the class or method is open or the mockk agent is configured. Here, compute() is final, so the stub is ignored and the default Int value 0 is returned.
Given a suspend function suspend fun fetch(): String, which code correctly mocks it to return "hello"?
MockK has special functions for suspend functions.
For mocking suspend functions, coEvery is used to stub the call. Option C uses coEvery correctly. Option C misuses every with runBlocking. Option C uses every which does not work with suspend functions. Option C uses coVerify which is for verification, not stubbing.
Given this code, how many times was service.process() called?
import io.mockk.mockk import io.mockk.verify class Service { fun process() {} } fun main() { val service = mockk<Service>(relaxed = true) service.process() service.process() service.process() verify(exactly = 2) { service.process() } }
Count the calls and compare with the verification count.
The function process() is called 3 times, but the verification expects exactly 2 calls. This mismatch causes MockK to throw a MockKException.