Unit tests with JUnit and MockK
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
coEveryvsevery,slotcapture, 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.
slotis a notebook where the mock writes down the argument it received so you can check it after the call.relaxed = trueis 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:
- Arrange – create the system under test (SUT) and its dependencies.
- Act – call the method or function you are testing.
- Assert – check the return value and verify side effects.
MockK is the most widely used mocking library in Kotlin. Its core API:
| Call | Purpose |
|---|---|
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 v | Stub a regular function |
coEvery { m.s() } returns v | Stub 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 insrc/androidTest(device or emulator, slower). - JUnit 4 is still the Android default. Annotate with
@Test,@Before,@After. JUnit 5 annotations such as@BeforeEachor@TestFactoryneed 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.
everystubs regular functions;coEverystubssuspendfunctions. Calling asuspendfunction insideevery { }does not compile, because that block is not a suspend lambda.verifyandcoVerifydefault to "at least once". Addexactly = 1to catch a double call, orexactly = 0(orwasNot Calledfor a whole mock) to check something never happened.confirmVerified(mock)fails if the mock received calls that none of yourverifyblocks covered.relaxed = truereturns 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 = trueis a safer middle ground: onlyUnitfunctions are relaxed, anything that returns a value must still be stubbed.slot<T>()combined withcapture(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.
mockkObjectandmockkStaticchange global state. Undo them in@AfterwithunmockkAll()(orunmockkObject(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)
}
}coEveryandcoVerifyare needed becausefetchUseris asuspendfunction;everywould not compile here.coVerify(exactly = 1)guards against a retry or double-call bug that a barecoVerifywould miss, andconfirmVerifiedfails 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.runTestcomes fromkotlinx-coroutines-testand 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
- Order-confirmation tests used
mockk<PaymentGateway>(relaxed = true)and only stubbedcharge(). getTransactionId(): Stringwas 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 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 retry bug made
LoginUseCasecallsessionStore.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 test now uses
verify(exactly = 1) { sessionStore.save(any()) }followed byconfirmVerified(sessionStore). - Code review asks for an explicit count wherever the number of calls matters.
- The retry logic was fixed so
saveruns once per successful login.
Common mistakes
- Expecting every to work on a suspend function. It does not compile, because the
everyblock is not a suspend lambda. UsecoEveryandcoVerifyforsuspendfunctions. - 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
clearMocksin@Before. - Over-mocking a stateful dependency. Mocking a cache or repository with many
every/coEverystubs makes tests brittle and hard to read. Write a small hand-written fake that keeps the state in aMutableMapor 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
verifyor 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
-
In your Android project, create a data class
Order(val id: String, val total: Double)and an interfaceOrderRepositorywith one method:suspend fun fetchOrder(id: String): Order?. -
Create
GetOrderTotalUseCase(private val repo: OrderRepository)with asuspend fun execute(id: String): Double?that returnsrepo.fetchOrder(id)?.total. -
In
src/test, createGetOrderTotalUseCaseTestwith JUnit 4 annotations. Add aprivate val repo = mockk<OrderRepository>()field. -
Write a test
returns total when order exists: usecoEveryto stubfetchOrder("10")to returnOrder("10", 49.99). Callexecute("10")insiderunTest. Assert the result withassertEquals(49.99, result!!, 0.0). AddcoVerify(exactly = 1) { repo.fetchOrder("10") }andconfirmVerified(repo). -
Write a second test
captures the id passed to repository: create aslot<String>(), stubfetchOrder(capture(idSlot))to returnnull, callexecute("77"), and assertidSlot.captured == "77". -
Write a third test
returns null when order is missing: stubfetchOrder("99")to returnnull, callexecute("99"), and assert the result isnull. -
Run
./gradlew testand confirm all three tests pass. Then write a fourth version of the first test with a hand-writtenFakeOrderRepositoryinstead 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.