Bird
Raised Fist0
Kotlinprogramming~20 mins

Mocking with MockK in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MockK Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this MockK verification?

Consider the following Kotlin code using MockK. What will be printed?

Kotlin
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")
}
ACompilation error: missing import
BVerification passed
Cio.mockk.MockKException: no calls found for: Calculator#add(2, 3)
DRuntime error: NullPointerException
Attempts:
2 left
💡 Hint

Think about what relaxed = true means for the mock.

❓ Predict Output
intermediate
2:00remaining
What happens when verifying a call that did not happen?

What error will this code produce?

Kotlin
import io.mockk.mockk
import io.mockk.verify

class Service {
    fun fetchData(): String = "data"
}

fun main() {
    val service = mockk<Service>()
    verify { service.fetchData() }
}
Aio.mockk.MockKException: no calls found for: Service#fetchData()
BCompilation error: verify requires a block
CNo output, verification passes silently
DRuntime error: NullPointerException
Attempts:
2 left
💡 Hint

What happens if you verify a call that was never made?

🔧 Debug
advanced
2:00remaining
Why does this MockK stub not work as expected?

Look at this Kotlin code snippet. The stub is supposed to return 10 when compute() is called, but it returns 0 instead. Why?

Kotlin
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())
}
AThe mock is not relaxed, so it returns default Int value 0 instead of 10
BThe stub is correct; the output will be 10
CThe mockk library is not imported correctly, causing default return
DThe stub is ignored because compute() is final and cannot be mocked
Attempts:
2 left
💡 Hint

Consider Kotlin's default behavior for functions and MockK's handling of final methods.

📝 Syntax
advanced
2:00remaining
Which option correctly mocks a suspend function with MockK?

Given a suspend function suspend fun fetch(): String, which code correctly mocks it to return "hello"?

Aevery { runBlocking { mock.fetch() } } returns "hello"
BcoVerify { mock.fetch() } returns "hello"
CcoEvery { mock.fetch() } returns "hello"
Devery { mock.fetch() } returns "hello"
Attempts:
2 left
💡 Hint

MockK has special functions for suspend functions.

🚀 Application
expert
2:00remaining
How many times was the function called?

Given this code, how many times was service.process() called?

Kotlin
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() }
}
A3 times, but verification expects 2, so it throws an exception
B2 times, verification passes
C1 time, verification fails
D0 times, verification fails
Attempts:
2 left
💡 Hint

Count the calls and compare with the verification count.

Practice

(1/5)
1. What is the main purpose of using MockK in Kotlin testing?
easy
A. To create fake objects that simulate real ones for testing
B. To compile Kotlin code faster
C. To write UI layouts
D. To deploy Kotlin applications

Solution

  1. Step 1: Understand mocking concept

    Mocking means creating fake versions of objects to test code without using real dependencies.
  2. Step 2: Identify MockK's role

    MockK is a Kotlin library that helps create these fake objects easily for testing purposes.
  3. Final Answer:

    To create fake objects that simulate real ones for testing -> Option A
  4. Quick Check:

    MockK = mocking tool for fake objects [OK]
Hint: MockK is for faking objects in tests [OK]
Common Mistakes:
  • Confusing MockK with build or deployment tools
  • Thinking MockK is for UI design
  • Assuming MockK speeds up compilation
2. Which of the following is the correct way to create a mock of a class MyService using MockK?
easy
A. val mock = new MyService()
B. val mock = MockK<MyService>()
C. val mock = mockk<MyService>()
D. val mock = createMock<MyService>()

Solution

  1. Step 1: Recall MockK syntax for mocking

    MockK uses the function mockk<ClassName>() to create mocks.
  2. Step 2: Check each option

    val mock = mockk<MyService>() uses mockk<MyService>(), which is correct syntax. Others are invalid or not MockK functions.
  3. Final Answer:

    val mock = mockk<MyService>() -> Option C
  4. Quick Check:

    mockk<Class>() creates mock [OK]
Hint: Use mockk<Class>() to create mocks [OK]
Common Mistakes:
  • Using uppercase 'MockK' as a function
  • Trying to use 'new' keyword in Kotlin
  • Using non-existent functions like createMock
3. Given the following code snippet, what will be printed?
val mock = mockk<Calculator>()
every { mock.add(2, 3) } returns 10
println(mock.add(2, 3))
println(mock.add(1, 1))
medium
A. 10 Exception
B. 10 0
C. 10 null
D. 5 0

Solution

  1. Step 1: Understand mocking behavior setup

    The mock is told to return 10 when add(2, 3) is called.
  2. Step 2: Check calls and outputs

    Calling mock.add(2, 3) returns 10 as set. Calling mock.add(1, 1) has no behavior defined, so MockK throws an exception by default.
  3. Final Answer:

    10 Exception -> Option A
  4. Quick Check:

    Defined call returns 10; undefined call throws exception [OK]
Hint: Undefined mock calls throw exceptions by default [OK]
Common Mistakes:
  • Assuming undefined calls return 0 or null
  • Thinking all calls return the same mocked value
  • Ignoring that MockK throws exceptions on undefined calls
4. Identify the error in this MockK usage:
val mock = mockk<UserRepository>()
every { mock.getUser(any()) } returns User("Alice")
mock.getUser(1)
verify { mock.getUser(1) }
medium
A. Missing relaxed = true when creating mock
B. No error; code is correct
C. No verify block needed after calling mock
D. Incorrect use of any() matcher in every

Solution

  1. Step 1: Analyze mocking and stubbing

    The mock is created normally, and every sets behavior for any argument using any(), which is valid.
  2. Step 2: Check verification usage

    After calling mock.getUser(1), the verify block correctly checks that the method was called with argument 1.
  3. Final Answer:

    No error; code is correct -> Option B
  4. Quick Check:

    any() matcher and verify block used correctly [OK]
Hint: any() matcher works inside every; verify checks calls [OK]
Common Mistakes:
  • Thinking relaxed=true is always required
  • Confusing verify usage with unnecessary calls
  • Misusing any() matcher outside stubbing
5. You want to mock a Kotlin interface PaymentProcessor so that calling process(amount) returns "Success" only when amount is greater than 100, otherwise throws an exception. Which MockK setup achieves this?
hard
A. every { mock.process(match { it > 100 }) } returns "Success" every { mock.process(match { amount <= 100 }) } throws IllegalArgumentException()
B. every { mock.process(any()) } returns "Success"
C. every { mock.process(100) } returns "Success" every { mock.process(0) } throws IllegalArgumentException()
D. every { mock.process(gt(100)) } returns "Success" every { mock.process(ltEq(100)) } throws IllegalArgumentException()

Solution

  1. Step 1: Understand conditional mocking with matchers

    MockK supports argument matchers like gt() (greater than) and ltEq() (less than or equal) for conditions.
  2. Step 2: Evaluate options for correct matcher usage

    every { mock.process(gt(100)) } returns "Success" every { mock.process(ltEq(100)) } throws IllegalArgumentException() correctly uses gt(100) to return "Success" and ltEq(100) to throw exception, matching the requirement precisely.
  3. Final Answer:

    every { mock.process(gt(100)) } returns "Success" every { mock.process(ltEq(100)) } throws IllegalArgumentException() -> Option D
  4. Quick Check:

    Use gt() and ltEq() for conditional mocking [OK]
Hint: Use gt() and ltEq() matchers for numeric conditions [OK]
Common Mistakes:
  • Using match { } lambda instead of built-in matchers
  • Mocking only specific values, missing ranges
  • Returning success for all inputs ignoring conditions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard