0
0
Android Kotlinmobile~20 mins

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

Choose your learning style9 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