picking-test-doubles

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Picking Test Doubles — Prefer Fakes; Mocks for Interactions Only

选择 Test Double——优先使用 Fake;仅在验证交互时使用 Mock

Google has an unambiguous preference order for test doubles, stated three times on
/training/testing/fundamentals/test-doubles
. Most Android codebases over-mock and under-fake, which produces tests that pin implementation details (which methods were called) instead of behavior (what state the system landed in). This skill encodes the six doubles, the preference order verbatim, and a decision matrix for picking the right one. Framework-mechanics for the mocking libraries themselves live in sibling skills (
../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
,
../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md
).
Google 在
/training/testing/fundamentals/test-doubles
中三次明确陈述了针对 Test Double 的偏好顺序。大多数 Android 代码库会过度使用 Mock,却很少使用 Fake,导致测试绑定到实现细节(调用了哪些方法),而不是行为(系统最终处于什么状态)。本 skill 编码了六种 Test Double、逐字偏好顺序,以及用于选择正确替身的决策矩阵。Mocking 库本身的框架机制见同级 skill(
../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
、
../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md
)。

When to use this skill

何时应使用此 skill

  • The user asks "should I use a fake or a mock" / "Mockito or MockK" / "what's the difference between a stub and a spy".
  • The user is replacing a dependency in a test and is unsure which double to reach for.
  • The PR under review uses
    verify(repo).getUser(any())
    everywhere and the agent suspects over-mocking.
  • The user mentions
    Robolectric
    "shadows" and asks where they fit in the test-double taxonomy.
  • The user says "every { repo.getUser() } returns User('Alice')" with no behavior under test and the agent should suggest a fake.
  • 用户询问“应该使用 Fake 还是 Mock”/“Mockito 还是 MockK”/“Stub 和 Spy 有什么区别”。
  • 用户正在测试中替换某个依赖,但不确定应该选择哪一种 Test Double。
  • 待审查的 PR 到处都在使用
    verify(repo).getUser(any())
    ,并且 Agent 怀疑存在过度 Mock 的情况。
  • 用户提到 Robolectric 的 “shadows”,并询问它们在 Test Double 分类体系中的位置。
  • 用户只说“
    every { repo.getUser() } returns User('Alice')
    ”,但没有待测试的行为,此时 Agent 应建议使用 Fake。

When NOT to use this skill

何时不应使用此 skill

  • The user already picked a fake / mock and wants framework mechanics (
    whenever
    /
    every
    /
    verify
    /
    argumentCaptor
    ) — use
    ../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
    or
    ../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md
    .
  • The user is wiring Hilt to swap a binding — combine this skill with
    ../../strategies/applying-testing-strategies/SKILL.md
    (Hilt section).
  • The user is choosing what to test, not how — use
    ../../concepts/choosing-what-to-test/SKILL.md
    .
  • The user is debugging a Robolectric shadow that throws on a specific API — use
    ../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
    .
  • 用户已经选定 Fake 或 Mock,并希望了解框架机制(
    whenever
    /
    every
    /
    verify
    /
    argumentCaptor
    )——请使用
    ../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
    或
    ../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md
    。
  • 用户正在配置 Hilt 来替换 binding——请将本 skill 与
    ../../strategies/applying-testing-strategies/SKILL.md
    (Hilt 部分)结合使用。
  • 用户正在决定应该测试什么,而不是应该如何测试——请使用
    ../../concepts/choosing-what-to-test/SKILL.md
    。
  • 用户正在调试某个会抛出特定 API 异常的 Robolectric Shadow——请使用
    ../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
    。

Prerequisites

前置条件

  • A test target whose dependencies are injected (constructor injection or interface-based DI). Doubles cannot be substituted into hard-wired singletons without refactor.
  • mockito-core
    +
    mockito-kotlin
    or
    io.mockk:mockk
    on
    testImplementation
    if mocks/stubs/spies are needed. See
    ../../strategies/organizing-test-source-sets/SKILL.md
    .
  • For shadows:
    org.robolectric:robolectric
    on
    testImplementation
    plus
    testOptions.unitTests.includeAndroidResources = true
    .
  • 测试目标的依赖必须通过注入方式传入(构造函数注入或基于 interface 的 DI)。如果不进行重构,就无法将 Test Double 替换到硬编码的单例中。
  • 如果需要 Mock、Stub 或 Spy,应在
    testImplementation
    中配置
    mockito-core
    +
    mockito-kotlin
    或
    io.mockk:mockk
    。参见
    ../../strategies/organizing-test-source-sets/SKILL.md
    。
  • 对于 Shadow:在
    testImplementation
    中配置
    org.robolectric:robolectric
    ,并设置
    testOptions.unitTests.includeAndroidResources = true
    。

The six doubles (verbatim definitions)

六种 Test Double(逐字定义)

All six definitions below — Fake, Mock, Stub, Spy, Dummy, and Shadow — are verbatim from
developer.android.com/training/testing/fundamentals/test-doubles
. Shadow is the Robolectric-specific double Google's page calls out alongside the classic five.
以下六种定义——Fake、Mock、Stub、Spy、Dummy 和 Shadow——均逐字摘自
developer.android.com/training/testing/fundamentals/test-doubles
。Shadow 是 Robolectric 特有的 Test Double,Google 的页面将其与经典的五种 Test Double 一并介绍。

Fake — preferred

Fake——首选

"Fake: A test double that has a 'working' implementation of the class, but it is implemented in a way that makes it good for tests but unsuitable for production. Example: an in-memory database. Fakes don't require a mocking framework and are lightweight. They are preferred." —
developer.android.com/training/testing/fundamentals/test-doubles
“Fake:一种具有该类‘可用’实现,但实现方式适合测试而不适合生产环境的 Test Double。例如:内存数据库。Fake 不需要 mocking 框架,并且十分轻量。它们是首选。” —
developer.android.com/training/testing/fundamentals/test-doubles

Mock — for interaction verification

Mock——用于验证交互

"Mock: A test double that behaves how you program it to behave and that has expectations about its interactions. Mocks will fail tests if their interactions don't match the requirements that you define. Mocks are usually created with a mocking framework to achieve all this. Example: Verify that a method in a database was called exactly once." —
developer.android.com/training/testing/fundamentals/test-doubles
“Mock:一种按照编程设定行为,并对交互抱有预期的 Test Double。如果交互不符合所定义的要求,Mock 会使测试失败。Mock 通常通过 mocking 框架创建,以实现上述全部能力。例如:验证数据库中的某个方法恰好被调用了一次。” —
developer.android.com/training/testing/fundamentals/test-doubles

Stub — canned answers, no expectations

Stub——预设答案,不带预期

"Stub: A test double that behaves how you program it to behave but doesn't have expectations about its interactions. Usually created with a mocking framework. Fakes are preferred over stubs for simplicity." —
developer.android.com/training/testing/fundamentals/test-doubles
“Stub:一种按照编程设定行为,但对交互没有预期的 Test Double。通常通过 mocking 框架创建。为简洁起见,Fake 优先于 Stub。” —
developer.android.com/training/testing/fundamentals/test-doubles

Spy — wraps a real object

Spy——包装真实对象

"Spy: A wrapper over a real object which also keeps track of some additional information, similar to mocks. They are usually avoided for adding complexity. Fakes or mocks are therefore preferred over spies." —
developer.android.com/training/testing/fundamentals/test-doubles
“Spy:对真实对象的包装,同时还会像 Mock 一样跟踪一些额外信息。它们通常会因增加复杂性而被避免。因此,Fake 或 Mock 优先于 Spy。” —
developer.android.com/training/testing/fundamentals/test-doubles

Dummy — passed but never used

Dummy——传入但从不使用

"Dummy: A test double that is passed around but not used, such as if you just need to provide it as a parameter. Example: an empty function passed as a click callback." —
developer.android.com/training/testing/fundamentals/test-doubles
“Dummy:一种只被传递但不会被使用的 Test Double,例如只是为了提供某个参数。例如:作为点击回调传入的空函数。” —
developer.android.com/training/testing/fundamentals/test-doubles

Shadow — Robolectric's fake-via-bytecode

Shadow——Robolectric 通过字节码实现的 Fake

"Shadow: Fake used in Robolectric." —
developer.android.com/training/testing/fundamentals/test-doubles
A shadow replaces an Android framework class with a JVM implementation at the bytecode level —
ShadowSystemClock
,
ShadowLooper
,
ShadowApplication
. It is a fake by intent (working implementation, unsuitable for production), but uniquely scoped to Android framework classes the developer cannot otherwise substitute. See
../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
.
“Shadow:在 Robolectric 中使用的 Fake。” —
developer.android.com/training/testing/fundamentals/test-doubles
Shadow 会在字节码层面用 JVM 实现替换 Android framework class,例如
ShadowSystemClock
、
ShadowLooper
和
ShadowApplication
。从意图上看,它属于 Fake(具有可用实现,但不适合生产环境),但其适用范围独特,仅限开发者无法通过其他方式替换的 Android framework class。参见
../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
。

Preference order (cite this in PR reviews)

偏好顺序(可在 PR Review 中引用)

Three verbatim quotes from the same page form the preference order:
  1. "Fakes don't require a mocking framework and are lightweight. They are preferred."
  2. "Fakes are preferred over stubs for simplicity."
  3. "Fakes or mocks are therefore preferred over spies."
Synthesized:
Fake > Mock ≈ Stub > Spy
                 ↑ (mock when verifying interactions; stub when only canned data)
Dummies are not in the ordering — they are placeholders, not real test logic. Shadows are a fake-by-construction reserved for framework classes.
同一页面中的三段原文引用共同构成了偏好顺序:
  1. “Fake 不需要 mocking 框架,并且十分轻量。它们是首选。”
  2. “为简洁起见,Fake 优先于 Stub。”
  3. “因此,Fake 或 Mock 优先于 Spy。”
综合如下:
Fake > Mock ≈ Stub > Spy
                 ↑ (mock when verifying interactions; stub when only canned data)
Dummy 不参与这一顺序,因为它们只是占位符,并不包含真正的测试逻辑。Shadow 在构造上属于 Fake,但专门用于 framework class。

Concrete Android examples

具体的 Android 示例

Fake —
FakeUserRepository
with in-memory map

Fake——使用内存 Map 的
FakeUserRepository

The
/test-doubles
page renders a sample for a fake. MUST NOT copy the page's example verbatim — it contains the typo
val const UserAlice = User("Alice")
(correct Kotlin is
const val
, not
val const
). Verified in
tasks/research/R8-android-fundamentals.md
. Use this corrected, expanded version:
kotlin
// RIGHT — fake repository with an in-memory map
class FakeUserRepository : UserRepository {
    private val users = mutableMapOf<UserId, User>()

    override suspend fun get(id: UserId): User? = users[id]

    override suspend fun save(user: User) {
        users[user.id] = user
    }

    override fun observeAll(): Flow<List<User>> = flow {
        while (currentCoroutineContext().isActive) {
            emit(users.values.toList())
            delay(100)
        }
    }

    // Test-only seeding helpers; production interface does NOT expose these.
    fun seed(vararg users: User) {
        users.forEach { this.users[it.id] = it }
    }
    fun clear() = users.clear()
}

@Test
fun loadsSeededUser() = runTest {
    val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
    val vm = UserViewModel(repo)
    vm.load(UserId("u1"))
    assertEquals("Alice", vm.state.value.name)
}
The fake compiles into the test source set; production code never sees it. There are no
every { }
blocks, no mock initialization, no verification ceremony.
/test-doubles
页面给出了一个 Fake 示例。不得逐字复制该页面中的示例,因为其中包含拼写错误
val const UserAlice = User("Alice")
;正确的 Kotlin 写法是
const val
,而不是
val const
。此问题已在
tasks/research/R8-android-fundamentals.md
中得到验证。请使用以下修正并扩展后的版本:
kotlin
// RIGHT — fake repository with an in-memory map
class FakeUserRepository : UserRepository {
    private val users = mutableMapOf<UserId, User>()

    override suspend fun get(id: UserId): User? = users[id]

    override suspend fun save(user: User) {
        users[user.id] = user
    }

    override fun observeAll(): Flow<List<User>> = flow {
        while (currentCoroutineContext().isActive) {
            emit(users.values.toList())
            delay(100)
        }
    }

    // Test-only seeding helpers; production interface does NOT expose these.
    fun seed(vararg users: User) {
        users.forEach { this.users[it.id] = it }
    }
    fun clear() = users.clear()
}

@Test
fun loadsSeededUser() = runTest {
    val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
    val vm = UserViewModel(repo)
    vm.load(UserId("u1"))
    assertEquals("Alice", vm.state.value.name)
}
Fake 会编译到测试 source set 中,生产代码永远不会看到它。它没有
every { }
块、没有 Mock 初始化,也没有额外的验证流程。

Mock —
mockk<UserRepository>()
for interaction verification

Mock——使用
mockk<UserRepository>()
验证交互

Reach for a mock when the interaction itself is the SUT, not the resulting state. Example: a sync engine that must call
markDirty(id)
exactly once after a save.
kotlin
@Test
fun save_marksDirty_exactlyOnce() = runTest {
    val repo = mockk<UserRepository>(relaxUnitFun = true)
    val syncQueue = mockk<SyncQueue>(relaxUnitFun = true)
    val sut = UserSaveOrchestrator(repo, syncQueue)

    sut.save(User(UserId("u1"), "Alice"))

    coVerify(exactly = 1) { syncQueue.markDirty(UserId("u1")) }
}
Mockito-kotlin equivalent (the canonical Android pattern per CORPUS Section G.3 — "400+ Kotlin files import org.mockito, zero import io.mockk" in the androidx checkout):
kotlin
@Test
fun save_marksDirty_exactlyOnce() = runTest {
    val repo: UserRepository = mock()
    val syncQueue: SyncQueue = mock()
    val sut = UserSaveOrchestrator(repo, syncQueue)

    sut.save(User(UserId("u1"), "Alice"))

    verify(syncQueue).markDirty(UserId("u1"))
    verifyNoMoreInteractions(syncQueue)
}
当交互本身才是 SUT,而不是最终状态才是测试重点时,应使用 Mock。例如,同步引擎必须在保存后恰好调用一次
markDirty(id)
。
kotlin
@Test
fun save_marksDirty_exactlyOnce() = runTest {
    val repo = mockk<UserRepository>(relaxUnitFun = true)
    val syncQueue = mockk<SyncQueue>(relaxUnitFun = true)
    val sut = UserSaveOrchestrator(repo, syncQueue)

    sut.save(User(UserId("u1"), "Alice"))

    coVerify(exactly = 1) { syncQueue.markDirty(UserId("u1")) }
}
Mockito-kotlin 的等价写法(根据 CORPUS 第 G.3 节,这是 Android 的标准模式——在
androidx/
checkout 中有“400 多个 Kotlin 文件导入
org.mockito
,没有文件导入
io.mockk
”):
kotlin
@Test
fun save_marksDirty_exactlyOnce() = runTest {
    val repo: UserRepository = mock()
    val syncQueue: SyncQueue = mock()
    val sut = UserSaveOrchestrator(repo, syncQueue)

    sut.save(User(UserId("u1"), "Alice"))

    verify(syncQueue).markDirty(UserId("u1"))
    verifyNoMoreInteractions(syncQueue)
}

Stub — canned data, no verification

Stub——预设数据,不进行验证

Use when the only thing the test needs is a return value, and you cannot conveniently write a fake.
kotlin
@Test
fun loadsCachedAvatarUrl() = runTest {
    val avatarApi: AvatarApi = mock()
    whenever(avatarApi.getUrl(UserId("u1"))).thenReturn("https://cdn/u1.png")

    val sut = AvatarPresenter(avatarApi)
    sut.load(UserId("u1"))

    assertEquals("https://cdn/u1.png", sut.url.value)
    // Note: no verify {} — this is a stub, not a mock.
}
If
AvatarApi
had multiple methods or the test needed to seed many calls, swap the stub for a
FakeAvatarApi
per the preference order.
当测试唯一需要的是某个返回值,并且不方便编写 Fake 时,使用 Stub。
kotlin
@Test
fun loadsCachedAvatarUrl() = runTest {
    val avatarApi: AvatarApi = mock()
    whenever(avatarApi.getUrl(UserId("u1"))).thenReturn("https://cdn/u1.png")

    val sut = AvatarPresenter(avatarApi)
    sut.load(UserId("u1"))

    assertEquals("https://cdn/u1.png", sut.url.value)
    // Note: no verify {} — this is a stub, not a mock.
}
如果
AvatarApi
有多个方法,或者测试需要植入大量调用数据,则应按照偏好顺序将 Stub 替换为
FakeAvatarApi
。

Spy — wrap a real object (avoid)

Spy——包装真实对象(应避免)

Spies are listed as "usually avoided for adding complexity". A legitimate use is partial replacement of a hard-to-fake class where the developer cannot justify a full fake. Even then, refactor the class first if possible.
kotlin
// WORKS but DISCOURAGED
val realCache = LruCache<String, Bitmap>(8)
val spied = spyk(realCache)
every { spied.evictAll() } answers { /* no-op for the test */ }
The spy lets the test override one method while keeping the rest real. The cost is hidden coupling: the test now relies on
LruCache
's real behavior for everything except
evictAll
, and any refactor of either side breaks tests in non-obvious ways.
Spy 被列为“通常会因增加复杂性而被避免”。一种合理用法是部分替换某个难以 Fake 的类,并且开发者无法为完整 Fake 找到充分理由。即使如此,也应尽可能先重构该类。
kotlin
// WORKS but DISCOURAGED
val realCache = LruCache<String, Bitmap>(8)
val spied = spyk(realCache)
every { spied.evictAll() } answers { /* no-op for the test */ }
Spy 允许测试覆盖一个方法,同时保留其余真实行为。其代价是隐藏耦合:除
evictAll
之外,测试仍依赖
LruCache
的真实行为,而任何一侧的重构都可能以难以理解的方式破坏测试。

Dummy — placeholder argument

Dummy——占位参数

kotlin
val noOpClickHandler: () -> Unit = {}   // dummy — type-checks, never invoked
val sut = ClickableComponent(onClick = noOpClickHandler)
sut.bind(...)  // test does not interact with onClick at all
kotlin
val noOpClickHandler: () -> Unit = {}   // dummy — type-checks, never invoked
val sut = ClickableComponent(onClick = noOpClickHandler)
sut.bind(...)  // test does not interact with onClick at all

Shadow —
ShadowSystemClock
as a fake-via-bytecode

Shadow——以
ShadowSystemClock
为例实现通过字节码替换的 Fake

When the SUT calls
SystemClock.uptimeMillis()
directly, abstracting it would require refactor; Robolectric ships a shadow that the test drives explicitly:
kotlin
@RunWith(AndroidJUnit4::class)
class TimerTest {
    @Test
    fun reportsElapsedTime() {
        ShadowSystemClock.setCurrentTimeMillis(0)
        val timer = Timer()
        ShadowSystemClock.advanceBy(Duration.ofMillis(1500))
        assertEquals(1500L, timer.elapsed())
    }
}
ShadowSystemClock
IS a fake (in-memory implementation, unsuitable for production) — it is just delivered as a Robolectric shadow because the production code calls a
final
Android framework method that no DI seam can intercept.
当 SUT 直接调用
SystemClock.uptimeMillis()
时,进行抽象将需要重构;Robolectric 提供了一个可由测试显式控制的 Shadow:
kotlin
@RunWith(AndroidJUnit4::class)
class TimerTest {
    @Test
    fun reportsElapsedTime() {
        ShadowSystemClock.setCurrentTimeMillis(0)
        val timer = Timer()
        ShadowSystemClock.advanceBy(Duration.ofMillis(1500))
        assertEquals(1500L, timer.elapsed())
    }
}
ShadowSystemClock
就是 Fake(内存实现,不适合生产环境)。它之所以以 Robolectric Shadow 的形式提供,是因为生产代码调用了 final Android framework method,而任何 DI seam 都无法拦截该调用。

Decision matrix

决策矩阵

The intent of the test                                     Pick
----------------------------------------------------------------
Need a working substitute for a class with state           Fake
  (in-memory DB, in-memory user map, in-memory clock)
Need to verify a specific interaction happened             Mock
  ("markDirty was called once with id u1")
Need a canned return value, no behavior, no verification   Stub
  (and a Fake would be heavyweight for this one method)
Need partial real / partial fake on the same class         Spy (last resort; refactor preferred)
Need a placeholder so a parameter type-checks              Dummy
Need to substitute an Android framework class (final API)  Shadow (Robolectric)
If two doubles fit, pick the one earlier in the preference list.
The intent of the test                                     Pick
----------------------------------------------------------------
Need a working substitute for a class with state           Fake
  (in-memory DB, in-memory user map, in-memory clock)
Need to verify a specific interaction happened             Mock
  ("markDirty was called once with id u1")
Need a canned return value, no behavior, no verification   Stub
  (and a Fake would be heavyweight for this one method)
Need partial real / partial fake on the same class         Spy (last resort; refactor preferred)
Need a placeholder so a parameter type-checks              Dummy
Need to substitute an Android framework class (final API)  Shadow (Robolectric)
如果两种 Test Double 都能满足需求,应选择偏好列表中更靠前的一种。

Patterns

模式

Pattern: WRONG vs RIGHT — fake vs mock for state

模式:错误 vs 正确——针对状态使用 Fake 还是 Mock

kotlin
// WRONG — using a mock to provide state
@Test
fun loadsAndDisplaysFirstUser() = runTest {
    val repo = mockk<UserRepository>()
    coEvery { repo.get(UserId("u1")) } returns User(UserId("u1"), "Alice")
    coEvery { repo.get(UserId("u2")) } returns User(UserId("u2"), "Bob")
    coEvery { repo.observeAll() } returns flowOf(
        listOf(User(UserId("u1"), "Alice"), User(UserId("u2"), "Bob"))
    )

    val vm = UserViewModel(repo)
    vm.load(UserId("u1"))
    assertEquals("Alice", vm.state.value.name)
}
// WRONG because: the test uses a mocking framework purely to seed data. Per /test-doubles:
// "Fakes are preferred over stubs for simplicity" and stubs are at least the lighter form
// of mock-as-data-source. A FakeUserRepository compiles, has no every {} ceremony, and
// the seed helper is reusable across tests.
kotlin
// RIGHT — fake provides state; ViewModel test asserts state
@Test
fun loadsAndDisplaysFirstUser() = runTest {
    val repo = FakeUserRepository().apply {
        seed(User(UserId("u1"), "Alice"), User(UserId("u2"), "Bob"))
    }
    val vm = UserViewModel(repo)
    vm.load(UserId("u1"))
    assertEquals("Alice", vm.state.value.name)
}
kotlin
// WRONG — using a mock to provide state
@Test
fun loadsAndDisplaysFirstUser() = runTest {
    val repo = mockk<UserRepository>()
    coEvery { repo.get(UserId("u1")) } returns User(UserId("u1"), "Alice")
    coEvery { repo.get(UserId("u2")) } returns User(UserId("u2"), "Bob")
    coEvery { repo.observeAll() } returns flowOf(
        listOf(User(UserId("u1"), "Alice"), User(UserId("u2"), "Bob"))
    )

    val vm = UserViewModel(repo)
    vm.load(UserId("u1"))
    assertEquals("Alice", vm.state.value.name)
}
// WRONG because: the test uses a mocking framework purely to seed data. Per /test-doubles:
// "Fakes are preferred over stubs for simplicity" and stubs are at least the lighter form
// of mock-as-data-source. A FakeUserRepository compiles, has no every {} ceremony, and
// the seed helper is reusable across tests.
错误原因:该测试纯粹使用 mocking 框架来植入数据。根据
/test-doubles
:“为简洁起见,Fake 优先于 Stub”,而 Stub 至少是将 Mock 当作数据源时更轻量的形式。
FakeUserRepository
可以直接编译,没有
every {}
样板代码,并且其 seed 辅助方法可以在多个测试之间复用。
kotlin
// RIGHT — fake provides state; ViewModel test asserts state
@Test
fun loadsAndDisplaysFirstUser() = runTest {
    val repo = FakeUserRepository().apply {
        seed(User(UserId("u1"), "Alice"), User(UserId("u2"), "Bob"))
    }
    val vm = UserViewModel(repo)
    vm.load(UserId("u1"))
    assertEquals("Alice", vm.state.value.name)
}

Pattern: WRONG vs RIGHT — verification on a fake

模式:错误 vs 正确——在 Fake 上进行验证

kotlin
// WRONG — verifying a method call on a fake
@Test
fun save_callsRepository() = runTest {
    val repo = FakeUserRepository()
    val sut = UserSaveOrchestrator(repo)
    sut.save(User(UserId("u1"), "Alice"))

    // Now the test wants to verify save() was called. Fakes don't track calls.
    // Tempting fix: switch to spyk(repo). DON'T.
    val tracking = spyk(repo)
    coVerify { tracking.save(any()) }
}
// WRONG because: this confuses "did the right state result?" (fake territory) with
// "was the right method called?" (mock territory). Pick one. If the test is verifying
// state, assert on repo.get(UserId("u1")) instead. If the test is verifying interaction,
// drop the fake and use a mock.
kotlin
// RIGHT — fake answers state assertions
@Test
fun save_persistsUser() = runTest {
    val repo = FakeUserRepository()
    val sut = UserSaveOrchestrator(repo)
    sut.save(User(UserId("u1"), "Alice"))

    assertEquals(User(UserId("u1"), "Alice"), repo.get(UserId("u1")))
}

// RIGHT — mock answers interaction assertions (separate test)
@Test
fun save_emitsSyncSignal() = runTest {
    val repo: UserRepository = mock()
    val syncQueue: SyncQueue = mock()
    val sut = UserSaveOrchestrator(repo, syncQueue)
    sut.save(User(UserId("u1"), "Alice"))

    verify(syncQueue).markDirty(UserId("u1"))
}
kotlin
// WRONG — verifying a method call on a fake
@Test
fun save_callsRepository() = runTest {
    val repo = FakeUserRepository()
    val sut = UserSaveOrchestrator(repo)
    sut.save(User(UserId("u1"), "Alice"))

    // Now the test wants to verify save() was called. Fakes don't track calls.
    // Tempting fix: switch to spyk(repo). DON'T.
    val tracking = spyk(repo)
    coVerify { tracking.save(any()) }
}
// WRONG because: this confuses "did the right state result?" (fake territory) with
// "was the right method called?" (mock territory). Pick one. If the test is verifying
// state, assert on repo.get(UserId("u1")) instead. If the test is verifying interaction,
// drop the fake and use a mock.
错误原因:这混淆了“最终是否得到了正确状态?”(Fake 的范畴)与“是否调用了正确的方法?”(Mock 的范畴),二者应选择其一。如果测试验证状态,应改为断言
repo.get(UserId("u1"))
;如果测试验证交互,则应弃用 Fake 并使用 Mock。
kotlin
// RIGHT — fake answers state assertions
@Test
fun save_persistsUser() = runTest {
    val repo = FakeUserRepository()
    val sut = UserSaveOrchestrator(repo)
    sut.save(User(UserId("u1"), "Alice"))

    assertEquals(User(UserId("u1"), "Alice"), repo.get(UserId("u1")))
}

// RIGHT — mock answers interaction assertions (separate test)
@Test
fun save_emitsSyncSignal() = runTest {
    val repo: UserRepository = mock()
    val syncQueue: SyncQueue = mock()
    val sut = UserSaveOrchestrator(repo, syncQueue)
    sut.save(User(UserId("u1"), "Alice"))

    verify(syncQueue).markDirty(UserId("u1"))
}

Pattern: WRONG vs RIGHT — overusing a spy

模式:错误 vs 正确——过度使用 Spy

kotlin
// WRONG
val cache = spyk(LruCache<String, Bitmap>(8))
every { cache.put(any(), any()) } answers {
    // intercept and log
    println("put: ${invocation.args[0]}")
    callOriginal()
}
WRONG because: per
/test-doubles
, spies "are usually avoided for adding complexity. Fakes or mocks are therefore preferred over spies". The interceptor here belongs in a fake LRU implementation that records calls in a list the test can assert on.
kotlin
// RIGHT
class RecordingCache : Cache<String, Bitmap> {
    val puts = mutableListOf<Pair<String, Bitmap>>()
    override fun put(key: String, value: Bitmap) { puts += key to value }
    override fun get(key: String): Bitmap? = null
}
kotlin
// WRONG
val cache = spyk(LruCache<String, Bitmap>(8))
every { cache.put(any(), any()) } answers {
    // intercept and log
    println("put: ${invocation.args[0]}")
    callOriginal()
}
错误原因:根据
/test-doubles
,Spy“通常会因增加复杂性而被避免。因此,Fake 或 Mock 优先于 Spy”。这里的拦截器应放在一个 Fake LRU 实现中,由该实现将调用记录到列表中,供测试断言。
kotlin
// RIGHT
class RecordingCache : Cache<String, Bitmap> {
    val puts = mutableListOf<Pair<String, Bitmap>>()
    override fun put(key: String, value: Bitmap) { puts += key to value }
    override fun get(key: String): Bitmap? = null
}

Pattern: WRONG vs RIGHT — Hilt + fake binding

模式:错误 vs 正确——Hilt 与 Fake binding

kotlin
// WRONG — production module with no test override
@Module @InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
    @Binds abstract fun bind(impl: RealUserRepository): UserRepository
}

@HiltAndroidTest
class HomeScreenTest {
    @Inject lateinit var repo: UserRepository      // real repo, real DB, slow + non-hermetic
    // ...
}
kotlin
// RIGHT — replace at the module boundary
@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [RepositoryModule::class],
)
abstract class FakeRepositoryModule {
    @Binds abstract fun bind(fake: FakeUserRepository): UserRepository
}
The fake compiles only into the test source set; production graph is untouched. See
../../strategies/applying-testing-strategies/SKILL.md
for the full Hilt rule-ordering pattern.
kotlin
// WRONG — production module with no test override
@Module @InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
    @Binds abstract fun bind(impl: RealUserRepository): UserRepository
}

@HiltAndroidTest
class HomeScreenTest {
    @Inject lateinit var repo: UserRepository      // real repo, real DB, slow + non-hermetic
    // ...
}
kotlin
// RIGHT — replace at the module boundary
@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [RepositoryModule::class],
)
abstract class FakeRepositoryModule {
    @Binds abstract fun bind(fake: FakeUserRepository): UserRepository
}
Fake 只会被编译到测试 source set 中,生产依赖图不会受到影响。有关完整的 Hilt 规则排序模式,请参见
../../strategies/applying-testing-strategies/SKILL.md
。

Mandatory rules

强制规则

  • MUST prefer fakes over mocks/stubs for substituting state-bearing dependencies. Per
    /test-doubles
    : "Fakes ... are preferred".
  • MUST prefer mocks over stubs/spies for interaction assertions. Stubs are mocks-without-verification; if no interaction is being verified, switch to a fake.
  • MUST NOT use a spy unless every other double is impractical and the cost of the partial-real coupling is documented in the test.
  • MUST NOT verify framework or library calls. (See
    ../../concepts/choosing-what-to-test/SKILL.md
    "What NOT to test".)
  • MUST NOT copy the
    FakeUserRepository
    snippet from
    /test-doubles
    verbatim — it contains the syntax error
    val const UserAlice = User(...)
    . Use
    private val
    or
    const val
    (in that order).
  • PREFERRED: keep one canonical
    FakeXRepository
    per repository interface in a
    testFixtures
    source set or a shared
    core-testing
    module; reuse it across ViewModel tests.
  • PREFERRED: when a class is hard to fake, refactor it (extract an interface) before reaching for a spy.
  • PREFERRED: Mockito-kotlin (
    mock<T>()
    ,
    whenever
    ,
    argumentCaptor
    ) for new code on Android — it is the de-facto standard in
    androidx/
    itself per CORPUS §G.3. Reach for MockK only when Kotlin-specific features (coroutines, top-level functions, sealed mocking) demand it.
  • 在替换持有状态的依赖时,必须优先使用 Fake,而不是 Mock 或 Stub。根据
    /test-doubles
    :“Fake……是首选”。
  • 进行交互断言时,必须优先使用 Mock,而不是 Stub 或 Spy。Stub 是没有验证的 Mock;如果没有验证任何交互,就应改用 Fake。
  • 绝不能使用 Spy,除非其他所有 Test Double 都不可行,并且在测试中记录了部分真实耦合的代价。
  • 绝不能验证 framework 或 library 调用。参见
    ../../concepts/choosing-what-to-test/SKILL.md
    中的“ What NOT to test”。
  • 绝不能逐字复制
    /test-doubles
    中的
    FakeUserRepository
    代码片段,因为其中包含 Kotlin 语法错误
    val const UserAlice = User(...)
    。请使用
    private val
    或
    const val
    ,并保持这一顺序。
  • 首选:在
    testFixtures
    source set 或共享的
    core-testing
    module 中,为每个 repository interface 保留一个规范的
    FakeXRepository
    ,并在 ViewModel 测试之间复用。
  • 首选:当某个类难以 Fake 时,应先重构它(提取 interface),再考虑使用 Spy。
  • 首选:Android 新代码使用 Mockito-kotlin(
    mock<T>()
    、
    whenever
    、
    argumentCaptor
    )。根据 CORPUS 第 G.3 节,它是
    androidx/
    自身事实上的标准。只有在 coroutines、top-level functions、sealed mocking 等 Kotlin 特有功能提出要求时,才使用 MockK。

Verification

验证清单

  • Every
    mockk<X>()
    /
    mock<X>()
    in the suite either has a
    verify { }
    /
    verify(x)
    call (genuine mock) or has been replaced by a
    FakeX
    (was actually a fake-as-mock anti-pattern).
  • No test uses
    spyk(x)
    /
    spy(x)
    without an inline comment justifying why a fake or mock is impractical.
  • Each repository interface has at most one canonical
    FakeXRepository
    shared across tests.
  • No production code references
    Fake*
    classes (the test source set never leaks into release).
  • Hilt-based UI tests use
    @TestInstallIn
    or
    @UninstallModules
    +
    @BindValue
    to swap real bindings for fakes — never
    every { }
    on a real injected instance.
  • No copy of the broken
    val const UserAlice
    Kotlin from the
    /test-doubles
    page exists in the repo.
  • 测试套件中的每个
    mockk<X>()
    /
    mock<X>()
    要么包含
    verify { }
    /
    verify(x)
    调用(属于真正的 Mock),要么已被替换为
    FakeX
    (原本属于“以 Mock 形式使用的 Fake”这一反模式)。
  • 任何测试都未在缺少说明为什么 Fake 或 Mock 不可行的内联注释时使用
    spyk(x)
    /
    spy(x)
    。
  • 每个 repository interface 最多只有一个跨测试共享的规范
    FakeXRepository
    。
  • 没有生产代码引用
    Fake*
    class,确保测试 source set 不会泄漏到发布版本中。
  • 基于 Hilt 的 UI 测试使用
    @TestInstallIn
    或
    @UninstallModules
    +
    @BindValue
    将真实 binding 替换为 Fake,绝不对真实注入实例使用
    every { }
    。
  • 仓库中不存在损坏的
    /test-doubles
    页面 Kotlin 代码
    val const UserAlice
    的副本。

References

参考资料

  • developer.android.com/training/testing/fundamentals/test-doubles
    — verbatim definitions, the three preference quotes, the Hilt cross-link.
  • developer.android.com/training/testing/local-tests
    — "Caution: Complex mocks should be avoided. Instead, you can use different types of test doubles such as fakes, or Robolectric shadows".
  • developer.android.com/training/dependency-injection/hilt-testing
    —
    @TestInstallIn
    ,
    @UninstallModules
    ,
    @BindValue
    ,
    HiltAndroidRule
    ordered to execute first.
  • tasks/research/R8-android-fundamentals.md
    — verbatim test-double quotes plus the noted typo (
    val const UserAlice
    ) on Google's page.
  • developer.android.com/develop/ui/compose/testing
    — Compose-side test doubles (cross-cutting).
  • Software Engineering at Google, ch. 13 ("Test Doubles") — deeper rationale for preferring fakes. https://abseil.io/resources/swe-book
  • Sibling skills:
    ../../concepts/understanding-the-testing-pyramid/SKILL.md
    ,
    ../../concepts/choosing-what-to-test/SKILL.md
    ,
    ../../strategies/applying-testing-strategies/SKILL.md
    ,
    ../../strategies/organizing-test-source-sets/SKILL.md
    .
  • Cross-category (framework mechanics):
    ../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
    ,
    ../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md
    ,
    ../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
    ,
    ../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md
    ,
    ../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.md
    .
  • developer.android.com/training/testing/fundamentals/test-doubles
    ——Test Double 的逐字定义、三段偏好顺序引用及 Hilt 交叉链接。
  • developer.android.com/training/testing/local-tests
    ——“注意:应避免使用复杂的 Mock。相反,可以使用 Fake 或 Robolectric Shadow 等不同类型的 Test Double”。
  • developer.android.com/training/dependency-injection/hilt-testing
    ——
    @TestInstallIn
    、
    @UninstallModules
    、
    @BindValue
    以及要求优先执行的
    HiltAndroidRule
    。
  • tasks/research/R8-android-fundamentals.md
    ——Test Double 的逐字引用及 Google 页面上注明的拼写错误(
    val const UserAlice
    )。
  • developer.android.com/develop/ui/compose/testing
    ——Compose 侧的 Test Double(跨领域内容)。
  • Software Engineering at Google,第 13 章(“Test Doubles”)——进一步说明优先使用 Fake 的原因。https://abseil.io/resources/swe-book
  • 同级 skill:
    ../../concepts/understanding-the-testing-pyramid/SKILL.md
    、
    ../../concepts/choosing-what-to-test/SKILL.md
    、
    ../../strategies/applying-testing-strategies/SKILL.md
    、
    ../../strategies/organizing-test-source-sets/SKILL.md
    。
  • 跨类别内容(框架机制):
    ../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
    、
    ../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md
    、
    ../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
    、
    ../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md
    、
    ../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.md
    。