Bird
Raised Fist0
Android Kotlinmobile~20 mins

MockK for mocking in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: MockK Testing Screen
A simple screen to demonstrate how to use MockK to mock a dependency and verify interactions in Kotlin Android tests.
Target UI
-------------------------
| MockK Testing Screen   |
|-----------------------|
| [Run Test]            |
|                       |
| Result:               |
|                       |
-------------------------
Create a simple Kotlin class with a dependency interface
Use MockK to mock the dependency in a unit test
Verify that a method on the mock is called when the tested method runs
Display a button labeled 'Run Test' that triggers the test logic
Show the test result (Pass/Fail) on the screen
Starter Code
Android Kotlin
package com.example.mockktest

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MockKTestActivity : AppCompatActivity() {
    private lateinit var resultTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mockk_test)

        resultTextView = findViewById(R.id.resultTextView)
        val runTestButton: Button = findViewById(R.id.runTestButton)

        runTestButton.setOnClickListener {
            // TODO: Run the mock test and update resultTextView
        }
    }
}

// TODO: Define a simple interface and a class that uses it
// TODO: Write a function to run a MockK test verifying interaction
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
package com.example.mockktest

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import io.mockk.mockk
import io.mockk.verify
import io.mockk.every
import io.mockk.confirmVerified

interface Dependency {
    fun doWork()
}

class Worker(private val dependency: Dependency) {
    fun perform() {
        dependency.doWork()
    }
}

class MockKTestActivity : AppCompatActivity() {
    private lateinit var resultTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mockk_test)

        resultTextView = findViewById(R.id.resultTextView)
        val runTestButton: Button = findViewById(R.id.runTestButton)

        runTestButton.setOnClickListener {
            val result = runMockKTest()
            resultTextView.text = if (result) "Test Passed" else "Test Failed"
        }
    }

    private fun runMockKTest(): Boolean {
        val mockDependency = mockk<Dependency>(relaxed = true)
        val worker = Worker(mockDependency)

        worker.perform()

        return try {
            verify { mockDependency.doWork() }
            confirmVerified(mockDependency)
            true
        } catch (e: Exception) {
            false
        }
    }
}

We define an interface Dependency with a method doWork(). The Worker class takes a Dependency and calls doWork() inside its perform() method.

In the activity, we create a mock of Dependency using MockK with relaxed = true so it won't throw errors on unmocked calls. We then create a Worker with this mock and call perform().

We verify that doWork() was called on the mock using verify. If verification passes, we return true; otherwise false.

The button triggers this test and updates the UI text to show if the test passed or failed.

Final Result
Completed Screen
-------------------------
| MockK Testing Screen   |
|-----------------------|
| [Run Test]            |
|                       |
| Result: Test Passed    |
|                       |
-------------------------
User taps 'Run Test' button
App runs the mock test in background
Result text updates to 'Test Passed' if mock method was called
If verification fails, result text shows 'Test Failed'
Stretch Goal
Add a Snackbar message that briefly shows 'Test completed' after running the test
💡 Hint
Use Snackbar.make(view, "Test completed", Snackbar.LENGTH_SHORT).show() inside the button click listener after updating the result text

Practice

(1/5)
1. What is the main purpose of using MockK in Android Kotlin testing?
easy
A. To create fake objects that simulate real ones for testing
B. To speed up the app's UI animations
C. To generate random data for the app
D. To compile Kotlin code faster

Solution

  1. Step 1: Understand MockK's role

    MockK is a library used to create fake objects that imitate real objects in tests.
  2. Step 2: Identify the main use

    This helps test parts of the app separately without relying on real implementations.
  3. Final Answer:

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

    MockK purpose = Fake objects for testing [OK]
Hint: MockK fakes objects to isolate tests quickly [OK]
Common Mistakes:
  • Thinking MockK speeds up UI animations
  • Confusing MockK with data generators
  • Believing MockK affects compilation speed
2. Which of the following is the correct syntax to create a mock of a class MyClass using MockK?
easy
A. val mock = MockK<MyClass>()
B. val mock = mockk<MyClass>()
C. val mock = mock<MyClass>()
D. val mock = createMock<MyClass>()

Solution

  1. Step 1: Recall MockK mock creation syntax

    MockK uses the function mockk<T>() to create mocks of type T.
  2. Step 2: Match syntax to options

    val mock = mockk<MyClass>() matches the correct syntax exactly.
  3. Final Answer:

    val mock = mockk<MyClass>() -> Option B
  4. Quick Check:

    MockK mock creation = mockk<Type>() [OK]
Hint: Use mockk<Type>() to create mocks in MockK [OK]
Common Mistakes:
  • Using capitalized MockK instead of mockk
  • Using mock() which is from other libraries
  • Trying createMock() which is not in MockK
3. Given the code snippet:
val mock = mockk<Calculator>()
every { mock.add(2, 3) } returns 5
val result = mock.add(2, 3)

What is the value of result?
medium
A. Throws an exception
B. 0
C. 5
D. 2

Solution

  1. Step 1: Understand the mocking setup

    The line every { mock.add(2, 3) } returns 5 tells MockK to return 5 when add(2, 3) is called.
  2. Step 2: Check the method call

    The call mock.add(2, 3) matches the mocked behavior, so it returns 5.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    Mocked method returns set value = 5 [OK]
Hint: Mocked calls return specified values, not real logic [OK]
Common Mistakes:
  • Expecting real method logic to run
  • Assuming default 0 return for Int
  • Thinking mock throws error without setup
4. What is wrong with this MockK code snippet?
val mock = mockk<UserService>()
verify { mock.getUser() }
medium
A. mockk<UserService>() is invalid syntax
B. getUser() method cannot be verified
C. verify requires a return value setup
D. verify is called before any method call on mock

Solution

  1. Step 1: Understand verify usage

    The verify block checks if a method was called on the mock.
  2. Step 2: Check method call timing

    Here, verify is called before mock.getUser() is ever called, so verification fails.
  3. Final Answer:

    verify is called before any method call on mock -> Option D
  4. Quick Check:

    Verify needs method call before checking [OK]
Hint: Call method before verify to avoid errors [OK]
Common Mistakes:
  • Calling verify before method invocation
  • Thinking verify needs return setup
  • Believing all methods are unverifiable
5. You want to test a function that calls fetchData() on a mock and then processes the result. Which MockK feature lets you simulate fetchData() returning different values on consecutive calls?
hard
A. Using every with returnsMany
B. Using slot to capture arguments
C. Using andThen to chain return values
D. Using relaxed mocks to auto-return defaults

Solution

  1. Step 1: Identify feature for multiple returns

    MockK's returnsMany allows specifying a list of return values for consecutive calls.
  2. Step 2: Match feature to options

    Using every with returnsMany correctly pairs every with returnsMany to simulate different returns on calls.
  3. Final Answer:

    Using every with returnsMany -> Option A
  4. Quick Check:

    Multiple returns = every + returnsMany [OK]
Hint: Use returnsMany to mock multiple call results [OK]
Common Mistakes:
  • Confusing andThen with returnsMany
  • Using slot for return values instead of capturing
  • Relying on relaxed mocks for varied returns
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