Fakes vs mocks

Learn fakes vs mocks in Android Kotlin tests: why Google prefers fakes for repositories, when MockK mocks fit, and how to explain the choice in interviews. About 25 minutes.

Why it matters

  • A mocked repository hides data-layer bugs (null handling, pagination, error mapping) that crash in production but never appear in the test.
  • Google's Android guide on test doubles calls fakes the preferred double in most cases, for example a fake repository in ViewModel and use-case tests; mocks fit best where you must check an interaction or cannot easily fake the dependency.
  • Interviewers ask "fake vs mock" to check whether you understand what each test actually verifies: outcomes versus interactions.
  • Choosing wrong makes tests brittle (over-verified mocks) or gives false confidence (oversimplified fakes that skip error paths).

The simple explanation

  • A fake is a training dummy: it looks like the real thing and reacts to punches, but it is made of foam and stays in the gym.
  • A mock is a camera on the wall: it records whether you threw a punch, but it does not react.
  • You use the dummy to practise your technique (test logic).
  • You use the camera to check you followed the choreography (test wiring).
  • Putting a camera where the dummy should be means you never practise the technique.

What is the difference between a fake and a mock? A fake is a working implementation of an interface with a shortcut inside: an in-memory MutableMap instead of a database, a fixed clock instead of System.currentTimeMillis(). Your test sets it up, runs the code, and checks the outcome. A mock is generated by a library such as MockK: you program what each call returns and then verify which calls happened. A stub is the same idea without the verification.

In Kotlin, mockk<T>() creates a mock, every { } (or coEvery { } for suspend functions) sets return values, and verify { } / coVerify { } checks interactions. spyk() wraps a real object, calls the real code by default and records calls.

Google's Android guide on test doubles marks fakes as preferred (and spies as usually avoided): a fake repository with in-memory data is the standard way to test ViewModels and use cases. Mocks are still useful when the interaction itself is the behaviour (an analytics event was sent, a callback was called) or when a dependency, such as a third-party SDK, is hard to fake.

AspectFakeMock
LogicWorking, simplifiedProgrammed per test
StateYes (in-memory)Optional
VerifiesOutcomesInteractions
Best forRepositories, data sourcesChecking an interaction, hard-to-fake SDKs
RiskDrifts from real implHides logic bugs

In Hilt tests, use @TestInstallIn, @UninstallModules or @BindValue to bind a fake in the test component. For pure use-case tests, skip Hilt and pass the fake through the constructor. Robolectric is needed only when the fake or the class under test touches Android framework classes.

A useful question in code review: does this test check an outcome or only a sequence of calls? If it only checks calls on your own repository, a fake usually gives a stronger test.

Notes

  • A fake is a working implementation with a shortcut (in-memory map, fixed clock); tests assert on outcomes.
  • A mock is programmed per test and can verify calls; it checks interactions. A stub returns programmed values without verification.
  • Google's guide on test doubles prefers fakes in most cases, especially for repositories and data sources.
  • In MockK, mockk<T>() creates a mock, every { } / coEvery { } set behaviour, verify { } / coVerify { } check calls, spyk() wraps a real object and records calls.
  • Use a mock when the interaction is the behaviour you care about, such as "an analytics event was logged once".
  • Never mock a data class or a simple value type; pass the real instance. Mocking a data class adds zero value and obscures intent.
  • In Hilt tests, use @TestInstallIn, @UninstallModules or @BindValue to bind a fake; for pure use-case tests, construct the object directly and skip Hilt.
  • A fake that omits edge cases (null, empty list, error response) gives false confidence and lets production crashes through.
  • Shared mutable state in a fake across tests causes flakiness; create a new fake instance per test or reset it in @Before.
  • For suspend functions in MockK use coEvery and coVerify, and run the test body in runTest. Fakes need neither: their suspend functions just run.

Code example

This shows a FakeUserRepository with in-memory state, two use-case tests that exercise real logic, and a comment block illustrating where a mock belongs instead.

// UserRepository.kt
interface UserRepository {
    suspend fun getUser(id: String): User?
    suspend fun saveUser(user: User)
}
 
data class User(val id: String, val name: String)
 
// Fake: real logic, in-memory, zero I/O
class FakeUserRepository : UserRepository {
    private val store = mutableMapOf<String, User>()
    override suspend fun getUser(id: String): User? = store[id]
    override suspend fun saveUser(user: User) { store[user.id] = user }
}
 
class GetUserUseCase(private val repo: UserRepository) {
    suspend operator fun invoke(id: String): User? = repo.getUser(id)
}
 
// Test with fake — preferred for data-layer logic
class GetUserUseCaseTest {
    @Test
    fun `returns null for unknown id`() = runTest {
        val useCase = GetUserUseCase(FakeUserRepository())
        assertNull(useCase("missing"))
    }
 
    @Test
    fun `returns user after save`() = runTest {
        val repo = FakeUserRepository()
        repo.saveUser(User("1", "Ada"))
        assertEquals("Ada", GetUserUseCase(repo)("1")?.name)
    }
}
 
// A mock fits when the interaction is the behaviour, e.g. an analytics SDK:
// val analytics = mockk<Analytics>(relaxUnitFun = true)
// ... run the code under test ...
// verify(exactly = 1) { analytics.logEvent("profile_opened") }
  • FakeUserRepository uses a MutableMap so getUser and saveUser share state, mirroring a real database round-trip without I/O.
  • Each test creates a fresh FakeUserRepository(), avoiding shared-state flakiness between tests.
  • The trailing comment shows where a mock earns its place: the test cares that an event was logged exactly once, and there is no outcome to read back.

Run the idea in plain Kotlin

interface PaymentGateway {
  fun charge(amount: Int): Boolean
}

class FakePaymentGateway(private val balance: Int) : PaymentGateway {
  var chargedTotal = 0
  override fun charge(amount: Int): Boolean {
      if (amount <= 0 || amount > balance - chargedTotal) return false
      chargedTotal += amount
      return true
  }
}

class RecordingGateway(private val cannedResult: Boolean) : PaymentGateway {
  val calls = mutableListOf<Int>()
  override fun charge(amount: Int): Boolean {
      calls.add(amount)
      return cannedResult
  }
}

fun main() {
  val fake = FakePaymentGateway(balance = 100)
  val r1 = fake.charge(30)
  val r2 = fake.charge(80)
  println("Fake: charge 30 -> " + r1 + ", charge 80 -> " + r2 + " (total: " + fake.chargedTotal + ")")

  val mock = RecordingGateway(cannedResult = true)
  mock.charge(50)
  mock.charge(20)
  println("Mock: called " + mock.calls.size + " times with " + mock.calls.toString())
  println("Mock always returns: " + mock.charge(999))
}

Expected output:

Fake: charge 30 -> true, charge 80 -> false (total: 30)
Mock: called 2 times with [50, 20]
Mock always returns: true

The fake refuses the second charge because it tracks a balance; the recording double says yes to anything, even 999.

In production

Mocked repository hid a null-crash
  • Crash reports showed a NullPointerException from a !! in the profile ViewModel after a release.
  • The ViewModel test used a mock with coEvery { getUser(any()) } returns User(...), so every lookup succeeded.
  • The real repository returned null when the user had been deleted on the server, but no test ever exercised that path.
The fix
  • Replaced the mock with a FakeUserRepository that returns null for unknown ids.
  • Added a test for the null path and replaced the !! with a proper "user not found" UI state.
  • Moved the fake into a shared test-fixtures module so every feature's tests reuse the same behaviour.
Fake too simple missed pagination
  • Users reported that the feed stopped loading after the first 20 items.
  • The FakeFeedRepository always returned the full list, so the pagination offset logic was never exercised.
  • The real API paginates with a cursor parameter; the fake ignored it entirely.
The fix
  • Rewrote the fake to store a full list and return pages by cursor, including a null next cursor on the last page.
  • Added tests for the first page, a middle page, and the last page.
  • Added a local JVM test of the real Retrofit service against MockWebServer with recorded JSON, to catch drift between the fake and the real API.

Common mistakes

  • Mocking every dependency, including your own repositories. The test checks calls, not outcomes, and only the paths you stubbed. Null handling, error mapping and pagination bugs pass silently. Use fakes for your own data layer; use mocks where the interaction itself matters.
  • Fake models only the happy path. Tests give false confidence. A fake that never returns null, empty, or an error lets production crashes through. Model every branch the real implementation can take.
  • Verifying call order with verifyOrder. Tests break on any internal refactoring that reorders calls. Verify outcomes (the result the user sees), not the sequence of internal calls, unless the order is part of the contract.
  • Mocking a data class or value type. A data class has no behaviour to mock. Passing a real User("1", "Ada") is clearer and avoids accidental stubbing of equals or hashCode.
  • Sharing one fake instance across tests. Mutable state leaks between tests, causing order-dependent flakiness. Create a new fake per test or reset it in @Before.
  • Stubbing a suspend function with every. In MockK, every and verify take non-suspend lambdas, so calling a suspend function inside them does not compile. Use coEvery and coVerify, inside runTest.

Interview questions

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

“When do you choose a fake over a mock in Android testing?”

“What is the difference between mockk and spyk in MockK?”

“How would you test a Hilt-injected use case that depends on a repository?”

“A test passes with a mock but fails in production. What went wrong?”

Quiz

What does a fake do that a mock does not?

Which approach does Google's Android testing guide recommend for repository tests?

What does spyk() do in MockK?

What is the main risk of a fake that only models the happy path?

0 of 4 answered

Mini task

Convert a mocked repository test to a fake-based test (15 min)

  1. Find a test in your project that uses mockk<UserRepository>() (or any data-layer interface) with every { } stubs. If none exists, create a small UserRepository interface with suspend fun getUser(id: String): User? and a trivial use case.

  2. Write a FakeUserRepository in the test source set. It should hold a MutableMap<String, User> and implement getUser and saveUser with real logic. Add at least three states: a user present, a user absent (returns null), and an empty map.

  3. Rewrite the test to construct the use case with FakeUserRepository() instead of mockk<UserRepository>(). Remove all every { } and verify { } calls. Assert on the returned value, not on whether a method was called.

  4. Add an edge-case test: call getUser with an id that was never saved and assert the result is null. Then call saveUser and getUser again and assert the name matches.

  5. Run the test with ./gradlew :app:testDebugUnitTest --tests "*GetUserUseCaseTest". Confirm it passes on the JVM without Robolectric.

Done when: the test file contains zero calls to mockk, every, or verify; the fake covers present, absent and empty cases; and the tests pass as plain local tests.

Next: Screenshot testing