Unit tests with JUnit and MockK

Learn Android unit testing with JUnit and MockK to master stubbing, argument capturing, and verifying interactions while choosing between mocks and fakes. About 25 minutes.

Why it matters

  • Many Android teams gate merges on local unit tests in src/test; they run in seconds on the JVM, so they catch regressions before a device is involved.
  • Interviewers ask you to explain coEvery vs every, slot capture, relaxed mocks, and when a fake beats a mock; vague answers signal a shallow testing background.
  • Relaxed mocks and verifications without a count let tests pass while the code does something wrong, so you need to know exactly what each one checks.
  • Understanding the arrange-act-assert shape lets you read and extend any test suite you inherit, not just the ones you wrote.

The simple explanation

  • A mock is a scripted actor in a rehearsal: it only does what you told it to do and keeps a log of every line it was asked to say.
  • A fake is a prop gun: it looks and behaves like the real thing but uses a simple in-memory mechanism instead of real ammunition.
  • Arrange-act-assert is like a kitchen recipe: gather ingredients, cook, then taste.
  • slot is a notebook where the mock writes down the argument it received so you can check it after the call.
  • relaxed = true is like an actor who improvises any unscripted line instead of freezing; convenient but risky because the improvised answer is a placeholder, not real behaviour.

In Android, local unit tests live in src/test and run on the JVM. Instrumented tests live in src/androidTest and run on a device or emulator. JUnit 4 is still the default for both in new Android projects; you annotate methods with @Test and use @Before / @After for setup and teardown. JUnit 5 works for local tests only with extra Gradle setup (usually the community android-junit5 plugin), and AndroidX instrumented tests are built on JUnit 4.

The arrange-act-assert pattern structures each test:

  1. Arrange – create the system under test (SUT) and its dependencies.
  2. Act – call the method or function you are testing.
  3. Assert – check the return value and verify side effects.

MockK is the most widely used mocking library in Kotlin. Its core API:

CallPurpose
mockk<T>()Create a mock that throws MockKException for any call you did not stub
mockk<T>(relaxed = true)Mock that returns simple defaults for unstubbed calls
mockk<T>(relaxUnitFun = true)Only functions returning Unit are relaxed
every { m.f() } returns vStub a regular function
coEvery { m.s() } returns vStub a suspend function
verify { m.f() }Assert a call happened (at least once by default)
coVerify { m.s() }Assert a suspend call happened
confirmVerified(m)Fail if m had calls that no verify covered
slot<T>() + capture(slot)Capture an argument for later assertion
mockkObject(X) / mockkStatic(...)Mock a Kotlin object or top-level/static functions
unmockkAll()Undo every mockkObject, mockkStatic and mockkConstructor

A hand-written fake is a small class that implements the interface with in-memory state. For a repository, the site's default is a fake (see the repository pattern lesson): it is easy to read and keeps working when the SUT changes which methods it calls. Use a mock when the point of the test is the interaction itself, such as "the analytics tracker was called once with this event". If the arrange block keeps growing, the SUT probably has too many dependencies and may need splitting.

Notes

  • Local unit tests go in src/test (JVM, fast, no Android runtime). Instrumented tests go in src/androidTest (device or emulator, slower).
  • JUnit 4 is still the Android default. Annotate with @Test, @Before, @After. JUnit 5 annotations such as @BeforeEach or @TestFactory need the JUnit 5 setup and do nothing in a JUnit 4 run.
  • Arrange-act-assert: set up mocks and inputs, call the SUT, then assert the return value and verify side effects. Separate the three sections with blank lines or comments.
  • every stubs regular functions; coEvery stubs suspend functions. Calling a suspend function inside every { } does not compile, because that block is not a suspend lambda.
  • verify and coVerify default to "at least once". Add exactly = 1 to catch a double call, or exactly = 0 (or wasNot Called for a whole mock) to check something never happened.
  • confirmVerified(mock) fails if the mock received calls that none of your verify blocks covered.
  • relaxed = true returns simple values (0, false, "", Unit) and chained mocks for other types instead of throwing. A test can then pass on a code path you never really set up.
  • relaxUnitFun = true is a safer middle ground: only Unit functions are relaxed, anything that returns a value must still be stubbed.
  • slot<T>() combined with capture(slot) inside a stub lets you assert on the argument the mock received after the call.
  • Prefer a hand-written fake when the dependency holds state (cache, session, repository). A mock with many stubs is harder to read and breaks when call order changes.
  • mockkObject and mockkStatic change global state. Undo them in @After with unmockkAll() (or unmockkObject(X)), or the mock leaks into later tests.

Code example

This test class covers a GetUserNameUseCase that trims an id, asks a UserRepository for the user, and falls back to "Unknown". The first test stubs a success path with coEvery and verifies the call with coVerify(exactly = 1). The second uses a slot to check the trimmed id the repository received.

import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.confirmVerified
import io.mockk.mockk
import io.mockk.slot
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
 
data class User(val id: String, val name: String)
 
interface UserRepository {
    suspend fun fetchUser(id: String): User?
}
 
class GetUserNameUseCase(private val repository: UserRepository) {
    suspend operator fun invoke(rawId: String): String =
        repository.fetchUser(rawId.trim())?.name ?: "Unknown"
}
 
class GetUserNameUseCaseTest {
 
    // JUnit 4 creates a new instance of the class for every test, so this mock is fresh each time
    private val repository = mockk<UserRepository>()
    private val useCase = GetUserNameUseCase(repository)
 
    @Test
    fun `returns the name when the user exists`() = runTest {
        // Arrange
        coEvery { repository.fetchUser("42") } returns User(id = "42", name = "Alice")
 
        // Act
        val name = useCase("42")
 
        // Assert
        assertEquals("Alice", name)
        coVerify(exactly = 1) { repository.fetchUser("42") }
        confirmVerified(repository)
    }
 
    @Test
    fun `trims the id and falls back to Unknown`() = runTest {
        // Arrange
        val idSlot = slot<String>()
        coEvery { repository.fetchUser(capture(idSlot)) } returns null
 
        // Act
        val name = useCase("  99 ")
 
        // Assert
        assertEquals("99", idSlot.captured)
        assertEquals("Unknown", name)
    }
}
  • coEvery and coVerify are needed because fetchUser is a suspend function; every would not compile here.
  • coVerify(exactly = 1) guards against a retry or double-call bug that a bare coVerify would miss, and confirmVerified fails if the use case made any other call on the mock.
  • capture(idSlot) matches any argument and records it, so the second test can check the exact value the use case passed.
  • runTest comes from kotlinx-coroutines-test and gives the test a coroutine to call suspend functions from.

Run the idea in plain Kotlin

The same use case tested with a hand-written fake that records the ids it received, which is all a slot or verify gives you here.

data class User(val id: String, val name: String)

interface UserRepository {
  fun fetchUser(id: String): User?
}

class GetUserNameUseCase(private val repo: UserRepository) {
  operator fun invoke(rawId: String): String = repo.fetchUser(rawId.trim())?.name ?: "Unknown"
}

class FakeUserRepository(private val users: Map<String, User>) : UserRepository {
  val requestedIds = mutableListOf<String>()
  override fun fetchUser(id: String): User? {
      requestedIds += id
      return users[id]
  }
}

fun main() {
  val fake = FakeUserRepository(mapOf("42" to User("42", "Alice")))
  val useCase = GetUserNameUseCase(fake)

  println("Name for 42: " + useCase("42"))
  println("Name for 99: " + useCase("  99 "))
  println("Ids received: " + fake.requestedIds)
  println("Called exactly twice: " + (fake.requestedIds.size == 2))
}

Expected output:

Name for 42: Alice
Name for 99: Unknown
Ids received: [42, 99]
Called exactly twice: true

In production

Relaxed mock hid a blank receipt number
  • Order-confirmation tests used mockk<PaymentGateway>(relaxed = true) and only stubbed charge().
  • getTransactionId(): String was never stubbed, so the relaxed mock returned "" and the tests passed without ever checking the receipt.
  • In production a declined-then-retried payment returned a blank id, and users saw a confirmation screen with an empty receipt number.
The fix
  • The tests switched to a plain mockk<PaymentGateway>(), so any unstubbed call throws and shows which behaviour the test forgot to set up.
  • A new test stubs a blank transaction id and asserts that the screen state shows an error instead of a confirmation.
  • The confirmation logic now treats a blank id as a failed payment.
A verify without a count let a double save pass CI
  • A retry bug made LoginUseCase call sessionStore.save(session) twice per login.
  • The test used verify { sessionStore.save(any()) }, which only checks "at least once".
  • The test passed while the second save overwrote fresh session data with a stale copy.
The fix
  • The test now uses verify(exactly = 1) { sessionStore.save(any()) } followed by confirmVerified(sessionStore).
  • Code review asks for an explicit count wherever the number of calls matters.
  • The retry logic was fixed so save runs once per successful login.

Common mistakes

  • Expecting every to work on a suspend function. It does not compile, because the every block is not a suspend lambda. Use coEvery and coVerify for suspend functions.
  • Keeping mocks in a companion object or other shared place. JUnit 4 creates a new test class instance per test, so mocks in normal fields start clean. Mocks shared through a companion object keep their stubs and recorded calls between tests; create them per test or call clearMocks in @Before.
  • Over-mocking a stateful dependency. Mocking a cache or repository with many every/coEvery stubs makes tests brittle and hard to read. Write a small hand-written fake that keeps the state in a MutableMap or list instead.
  • Asserting only the return value. You miss bugs where the SUT returns the right value but forgets to call a callback, emit an event, or save something. Check side effects with verify or with the state of a fake.
  • Using mockkObject or mockkStatic without undoing it. The mocked singleton or static function stays mocked for later tests in the same JVM, causing failures that depend on test order. Call unmockkAll() in @After.
  • Testing private methods via reflection. This couples the test to implementation details and breaks on any refactor. Test the public behaviour; if a private method is hard to reach, extract it into a separate class with its own test.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between a mock and a fake?”

“When do you use coEvery instead of every?”

“What does relaxed = true do, and when is it dangerous?”

“How do you structure a test that uses arrange-act-assert?”

Quiz

Which directory holds local JVM unit tests in an Android module?

What does coEvery do in MockK?

What does slot<T>() do when used with capture inside a stub?

What happens when a relaxed mock receives a call to a function that was not stubbed?

0 of 4 answered

Mini task

15-minute exercise: test a use case with MockK

  1. In your Android project, create a data class Order(val id: String, val total: Double) and an interface OrderRepository with one method: suspend fun fetchOrder(id: String): Order?.

  2. Create GetOrderTotalUseCase(private val repo: OrderRepository) with a suspend fun execute(id: String): Double? that returns repo.fetchOrder(id)?.total.

  3. In src/test, create GetOrderTotalUseCaseTest with JUnit 4 annotations. Add a private val repo = mockk<OrderRepository>() field.

  4. Write a test returns total when order exists: use coEvery to stub fetchOrder("10") to return Order("10", 49.99). Call execute("10") inside runTest. Assert the result with assertEquals(49.99, result!!, 0.0). Add coVerify(exactly = 1) { repo.fetchOrder("10") } and confirmVerified(repo).

  5. Write a second test captures the id passed to repository: create a slot<String>(), stub fetchOrder(capture(idSlot)) to return null, call execute("77"), and assert idSlot.captured == "77".

  6. Write a third test returns null when order is missing: stub fetchOrder("99") to return null, call execute("99"), and assert the result is null.

  7. Run ./gradlew test and confirm all three tests pass. Then write a fourth version of the first test with a hand-written FakeOrderRepository instead of MockK and compare how they read.

Done condition: three MockK tests pass, each with clearly separated arrange, act, and assert sections, no test uses relaxed = true, and the fake-based version passes too.

Next: Testing coroutines and flows