CodeBlanks Logo Icon CodeBlanks

Advanced MockK

Learn advanced MockK with coEvery and coVerify.

MockK: coEvery and coVerify

MockK is a popular mocking library for Kotlin. For suspend functions, coEvery defines behavior and coVerify checks the call was made.

Example: coEvery { repo.fetchUser(1) } returns "Alex". This makes repo.fetchUser(1) return "Alex". At the end, coVerify { repo.fetchUser(1) } verifies the call. MockK lets you safely mock suspend calls in tests.

Capturing arguments with slot

MockK's slot feature captures an argument passed to a mock. It is useful for callbacks and suspend calls.

Example: val idSlot = slot<Int>(); coEvery { repo.fetchUser(capture(idSlot)) } returns "Alex". After the call, idSlot.captured gives the value passed in. This pattern lets you verify the real argument value afterward.

Practice Mock a suspend repository

Define an interface UserRepo with method suspend fun fetchUser(id: Int): String. In main create a mock with mockk<UserRepo>(), write coEvery { repo.fetchUser(1) } returns "Alex", and inside a runTest block call println(repo.fetchUser(1)).

Starter code

Main.kt
import kotlinx.coroutines.test.runTest
import io.mockk.mockk
import io.mockk.coEvery

// UserRepo interface: kullanıcı getirme metodu
// in main create a mock, define behavior with coEvery, print inside runTest

Sample solution

Main.kt
import kotlinx.coroutines.test.runTest
import io.mockk.mockk
import io.mockk.coEvery

interface UserRepo {
    suspend fun fetchUser(id: Int): String
}

fun main() {
    val repo = mockk<UserRepo>()
    coEvery { repo.fetchUser(1) } returns "Alex"
    runTest {
        println(repo.fetchUser(1))
    }
}

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which MockK function defines the return value of a suspend function?

  • given
  • every
  • when
  • coEvery Correct answer

Explanation: coEvery is for suspend functions.

2 Complete the coVerify call

Question
coEvery { repo.fetchUser(1) } returns "Alex"
// verify the call
____ { repo.fetchUser(1) }
Answer
coEvery { repo.fetchUser(1) } returns "Alex"
// verify the call
coVerify { repo.fetchUser(1) }

Explanation: coVerify verifies a suspend call.

3 Match the MockK parts

Term Meaning
coEvery { } Behavior definition
returns Return value
coVerify { } Call verification
slot<T>() Argument capture

All lessons in Advanced