applying-testing-strategies
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseApplying Testing Strategies — Determinism, Structure, and Hilt
应用测试策略——确定性、结构与 Hilt
A test suite needs three things to scale: it must be deterministic (same input → same outcome), structured (any reader can locate Given/When/Then), and replaceable (a single binding swap reroutes the production graph to fakes). This skill encodes Google's strategy guidance — flagging which page each rule actually lives on — and the Hilt mechanics that wire it into the build.
一个测试套件要实现可扩展性,需要具备三项特征:必须是 确定性(相同输入 → 相同结果)、结构化(任何读者都能找到 Given/When/Then),以及 可替换(只需替换一个 binding,即可将生产依赖图路由到 fake)。此 skill 梳理了 Google 的策略指导——明确每条规则实际所在的页面——以及将测试接入构建的 Hilt 机制。
When to use this skill
何时使用此 skill
- The user asks "how should I structure my Android tests" / "Given-When-Then or Arrange-Act-Assert" / "how do I name test methods".
- The user asks about ,
@HiltAndroidTest,HiltAndroidRule,@TestInstallIn,@UninstallModules, or rule ordering.@BindValue - The user reports "tests pass locally but fail on CI" — usually a determinism / hermeticity issue.
- The user is starting a new module and needs a strategy doc / convention list.
- The user mentions for combining
RuleChain.outerRulewithHiltAndroidRuleorActivityScenarioRule.composeTestRule
- 用户询问“应该如何组织 Android 测试” / “Given-When-Then 还是 Arrange-Act-Assert” / “如何命名测试方法”。
- 用户询问 、
@HiltAndroidTest、HiltAndroidRule、@TestInstallIn、@UninstallModules或 rule 顺序。@BindValue - 用户反馈“测试本地通过但在 CI 失败”——通常是确定性 / hermeticity 问题。
- 用户正在创建新 module,需要一份策略文档 / 约定清单。
- 用户提到使用 ,将
RuleChain.outerRule与HiltAndroidRule或ActivityScenarioRule组合起来。composeTestRule
When NOT to use this skill
何时不应使用此 skill
- The user is choosing scope (small/medium/big) — use .
../../concepts/understanding-the-testing-pyramid/SKILL.md - The user is choosing what behavior to cover — use .
../../concepts/choosing-what-to-test/SKILL.md - The user is choosing fakes vs mocks — use .
../../doubles/picking-test-doubles/SKILL.md - The user is wiring source sets — use .
../organizing-test-source-sets/SKILL.md - The user is debugging a single flaky Compose animation test — use .
../../../compose/synchronization/synchronizing-with-idle/SKILL.md
- 用户正在选择范围(small/medium/big)——使用 。
../../concepts/understanding-the-testing-pyramid/SKILL.md - 用户正在选择需要覆盖的行为——使用 。
../../concepts/choosing-what-to-test/SKILL.md - 用户正在选择 fake 还是 mock——使用 。
../../doubles/picking-test-doubles/SKILL.md - 用户正在配置 source set——使用 。
../organizing-test-source-sets/SKILL.md - 用户正在排查单个 flaky Compose animation test——使用 。
../../../compose/synchronization/synchronizing-with-idle/SKILL.md
Prerequisites
前置条件
- Familiarity with the small/medium/big pyramid framing from .
../../concepts/understanding-the-testing-pyramid/SKILL.md - A test target where dependencies are injected (Hilt, manual constructor injection, or another DI library).
- For the Hilt section: and
dagger.hilt.android.testing.HiltAndroidRuleavailable ondagger.hilt.android.testing.HiltAndroidTest.androidTestImplementation - For determinism: ,
kotlinx-coroutines-test(if host tests), and the ability to stubRobolectric/System.currentTimeMillis().Clock.systemDefaultZone()
- 熟悉 中的 small/medium/big 测试金字塔框架。
../../concepts/understanding-the-testing-pyramid/SKILL.md - 具备一个注入了依赖项的测试目标(Hilt、手动 constructor injection 或其他 DI library)。
- 对于 Hilt 部分:可通过 使用
androidTestImplementation和dagger.hilt.android.testing.HiltAndroidRule。dagger.hilt.android.testing.HiltAndroidTest - 对于确定性:、
kotlinx-coroutines-test(用于 host test),以及 stubRobolectric/System.currentTimeMillis()的能力。Clock.systemDefaultZone()
Source-of-truth map (which page says what)
事实来源映射(哪个页面说明了什么)
Per , the strategy concepts live on three different pages. Naming the source matters because PR reviewers cite skills.
tasks/research/R8-android-fundamentals.md| Concept | Page that actually documents it |
|---|---|
| Qualitative pyramid ("many small, few big") | |
| Five-level Unit/Component/Feature/Application/RC table | |
| Network access per layer | |
| Determinism / flake handling | |
| Hermetic test definition | |
| Given-When-Then comment style | NEVER named on any page; only used in code samples |
| Arrange-Act-Assert | NEVER named on any page |
| Test naming | Only the backtick caveat on |
| |
MUST NOT attribute determinism guidance to — it is on . MUST NOT claim Google "recommends Given-When-Then" — the pages do not say that; they only use the comment style in samples.
/strategies/instrumented-tests/stability根据 ,这些策略概念分布在三个不同页面上。说明来源很重要,因为 PR 评审者会引用 skills。
tasks/research/R8-android-fundamentals.md| 概念 | 实际记录该内容的页面 |
|---|---|
| 定性测试金字塔(“大量小测试,少量大测试”) | |
| 五级 Unit/Component/Feature/Application/RC 表 | |
| 各层级的网络访问 | |
| 确定性 / flaky 处理 | |
| Hermetic test 定义 | |
| Given-When-Then 注释风格 | 任何页面都未明确命名;仅在代码示例中使用 |
| Arrange-Act-Assert | 任何页面都未明确命名 |
| 测试命名 | 仅 |
| |
不得将确定性指导归到 ——它位于 。不得声称 Google “推荐 Given-When-Then”——这些页面并未这样表述;它们只在示例中使用这种注释风格。
/strategies/instrumented-tests/stabilityDeterminism
确定性
Per (and CORPUS §C "Common gotchas"), four sources of non-determinism dominate:
/training/testing/instrumented-tests/stability- Time — ,
System.currentTimeMillis(),Clock.systemDefaultZone(). Inject aInstant.now()or useClock's virtual time.kotlinx-coroutines-test - Concurrency / coroutines — direct ,
Dispatchers.IO, realrunBlocking. Usedelay, injectrunTest, replaceCoroutineDispatcherviaDispatchers.Main. SeeDispatchers.setMain(dispatcher).../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md - Animation / frame timing — Compose's , View animations. Disable via
MainTestClock(Gradle) ortestOptions.animationsDisabled = true(ADB). For Compose:Settings.Global.WINDOW_ANIMATION_SCALE = 0per the skydoves directives inmainClock.autoAdvance = false§5.docs/SPEC.md - External state — network, real DB, ,
Random(). Inject seeds, use fakes, runUUID.randomUUID()before each instrumented test.pm clear
Concrete checklist:
- (or equivalent time source) is injected; tests substitute
Clock.Clock.fixed(Instant.parse(...), ZoneId.of("UTC")) - are injected via a
Dispatchersinterface or replaced withDispatcherProviderin aDispatchers.setMain(StandardTestDispatcher()).@Before - is seeded (
Random) or wrapped behind aRandom(42)that the test substitutes.RandomProvider - is set in
testOptions.animationsDisabled = true.build.gradle.kts - CI runs before every instrumented test (Test Orchestrator does this automatically; otherwise add an
pm clear <pkg>).@Before
根据 (以及 CORPUS §C“常见陷阱”),以下四类非确定性来源占主导:
/training/testing/instrumented-tests/stability- Time——、
System.currentTimeMillis()、Clock.systemDefaultZone()。应注入Instant.now(),或使用Clock的 virtual time。kotlinx-coroutines-test - Concurrency / coroutines——直接使用 、
Dispatchers.IO、真实的runBlocking。应使用delay、注入runTest,或通过CoroutineDispatcher替换Dispatchers.setMain(dispatcher)。参见Dispatchers.Main。../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md - Animation / frame timing——Compose 的 、View animation。可通过
MainTestClock(Gradle)或testOptions.animationsDisabled = true(ADB)禁用。对于 Compose,应按照Settings.Global.WINDOW_ANIMATION_SCALE = 0§5 中的 skydoves 指令设置docs/SPEC.md。mainClock.autoAdvance = false - External state——网络、真实 DB、、
Random()。应注入 seed、使用 fake,并在每次 instrumented test 前运行UUID.randomUUID()。pm clear
具体检查清单:
- 已注入 (或等效的时间源);测试使用
Clock进行替换。Clock.fixed(Instant.parse(...), ZoneId.of("UTC")) - 通过 interface 注入
DispatcherProvider,或在Dispatchers中使用@Before进行替换。Dispatchers.setMain(StandardTestDispatcher()) - 已为 设置 seed(
Random),或将其封装在测试可替换的Random(42)后面。RandomProvider - 已在 中设置
build.gradle.kts。testOptions.animationsDisabled = true - CI 在每次 instrumented test 前运行 (Test Orchestrator 会自动执行;否则需添加
pm clear <pkg>)。@Before
Hermetic vs integration
Hermetic 与 integration
The page does NOT formalize "hermetic" as a top-level term. The closest definition is on :
/strategies/test-doubles"A hermetic test avoids all external dependencies, such as fetching data from the internet." —developer.android.com/training/testing/fundamentals/test-doubles
The operational rule is on :
/strategies| Layer | Network access |
|---|---|
| Unit | None |
| Component | None |
| Feature | "supports mocked network access" |
| Application | n/a |
| Release Candidate | n/a |
MUST NOT present "hermetic" as if it were a dedicated section on — it is mentioned in passing on only. MUST cite both pages when discussing hermeticity: for the term, for the operational rule.
/strategies/test-doubles/test-doubles/strategies/strategies/test-doubles“Hermetic test 会避开所有外部依赖,例如从互联网获取数据。” —developer.android.com/training/testing/fundamentals/test-doubles
可操作的规则位于 :
/strategies| 层级 | 网络访问 |
|---|---|
| Unit | 无 |
| Component | 无 |
| Feature | “支持 mocked 网络访问” |
| Application | 不适用 |
| Release Candidate | 不适用 |
不得将“hermetic”描述为 上的独立章节——它只在 中被顺带提及。讨论 hermeticity 时,必须同时引用两个页面: 用于术语定义, 用于可操作的规则。
/strategies/test-doubles/test-doubles/strategiesGiven-When-Then / Arrange-Act-Assert
Given-When-Then / Arrange-Act-Assert
Neither pattern is named on any of the four primary pages (, , , ). They are visibly used in Google's code samples. From :
/fundamentals/what-to-test/test-doubles/strategies/fundamentalskotlin
// Given an instance of MyViewModel
val viewModel = MyViewModel(myFakeDataRepository)
// When data is loaded
viewModel.loadData()
// Then it should be exposing data
assertTrue(viewModel.data != null)— (Local/host-side unit test example)
developer.android.com/training/testing/fundamentalsAnd from the same page:
kotlin
// When the Continue button is clicked
onView(withText("Continue")).perform(click())
// Then the Welcome screen is displayed
onView(withText("Welcome")).check(matches(isDisplayed()))— (Espresso example)
developer.android.com/training/testing/fundamentalsCite "Google's official samples consistently use Given-When-Then comment blocks" — accurate. Do NOT cite "Google recommends Given-When-Then" — that is fabrication.
Both Given-When-Then and Arrange-Act-Assert are the same shape with different vocabulary:
Given (Arrange) — set up the SUT and dependencies
When (Act) — invoke the behavior under test
Then (Assert) — assert on the resulting state or interactionPick one vocabulary per repo (skydoves preference: Given-When-Then, matching Google's samples). Use it as inline comment blocks, not as method names.
这两种模式都没有在四个主要页面(、、、)中被明确命名,但它们在 Google 的代码示例中清晰可见。以下内容来自 :
/fundamentals/what-to-test/test-doubles/strategies/fundamentalskotlin
// Given an instance of MyViewModel
val viewModel = MyViewModel(myFakeDataRepository)
// When data is loaded
viewModel.loadData()
// Then it should be exposing data
assertTrue(viewModel.data != null)— (Local/host-side 单元测试示例)
developer.android.com/training/testing/fundamentals同一页面中的另一个示例:
kotlin
// When the Continue button is clicked
onView(withText("Continue")).perform(click())
// Then the Welcome screen is displayed
onView(withText("Welcome")).check(matches(isDisplayed()))— (Espresso 示例)
developer.android.com/training/testing/fundamentals可以说“Google 官方示例始终使用 Given-When-Then 注释块”——这一表述准确。不要说“Google 推荐 Given-When-Then”——那属于捏造。
Given-When-Then 和 Arrange-Act-Assert 的形态相同,只是术语不同:
Given (Arrange) — set up the SUT and dependencies
When (Act) — invoke the behavior under test
Then (Assert) — assert on the resulting state or interaction每个仓库选择一套术语(skydoves 偏好 Given-When-Then,与 Google 示例保持一致)。应将其作为行内注释块使用,而不是作为方法名。
Test naming
测试命名
The only verbatim naming guidance across the four primary pages is the backtick caveat on :
/instrumented-tests"Note: Using backticks to name tests in Kotlin is only supported on devices running API 30 and above." —developer.android.com/training/testing/instrumented-tests
Implications:
- Local tests () — backtick names are safe (run on JVM, not the Android runtime).
src/test/ - Instrumented tests () — backtick names require
src/androidTest/on the test APK. Below that, useminSdk >= 30orcamelCase.snake_case_with_underscores
skydoves convention (combine these two facts): a shape that reads as a sentence.
methodName_state_expectedloadUsers_emptyList_emitsEmptyState
applyCoupon_negativeTotal_emitsError
save_orchestratorMarksDirtyOnce四个主要页面中唯一逐字给出的命名指导,是 中的 backtick 注意事项:
/instrumented-tests“**注意:**在 Kotlin 中使用 backtick 命名测试,仅受运行 API 30 及以上版本的设备支持。” —developer.android.com/training/testing/instrumented-tests
这意味着:
- Local test()——可安全使用 backtick 名称(运行于 JVM,而非 Android runtime)。
src/test/ - Instrumented test()——backtick 名称要求测试 APK 的
src/androidTest/。低于该版本时,使用minSdk >= 30或camelCase。snake_case_with_underscores
skydoves 约定(结合上述两项事实):采用 格式,使其读起来像一句完整的话。
methodName_state_expectedloadUsers_emptyList_emitsEmptyState
applyCoupon_negativeTotal_emitsError
save_orchestratorMarksDirtyOnceHilt for testing — the full mechanic
Hilt 测试的完整机制
Source: plus CORPUS §F.6.
developer.android.com/training/dependency-injection/hilt-testing来源:,以及 CORPUS §F.6。
developer.android.com/training/dependency-injection/hilt-testingWhy Hilt for tests at all
为何测试中需要 Hilt
"Hilt isn't necessary for unit tests, since when testing a class that uses constructor injection, you don't need to use Hilt to instantiate that class." —developer.android.com/training/dependency-injection/hilt-testing
"For integration tests, Hilt injects dependencies as it would in your production code. Testing with Hilt requires no maintenance because Hilt automatically generates a new set of components for each test." —developer.android.com/training/dependency-injection/hilt-testing
So: constructor-inject in unit tests (skip Hilt), use Hilt in UI / integration tests.
“对于使用 constructor injection 的类进行单元测试时,不需要使用 Hilt 来实例化该类。” —developer.android.com/training/dependency-injection/hilt-testing
“对于 integration test,Hilt 会像生产代码中一样注入依赖项。使用 Hilt 进行测试无需维护,因为 Hilt 会为每个测试自动生成一组新的组件。” —developer.android.com/training/dependency-injection/hilt-testing
因此:单元测试采用 constructor injection(跳过 Hilt),UI / integration test 使用 Hilt。
@HiltAndroidTest
+ HiltAndroidRule
ordered first
@HiltAndroidTestHiltAndroidRule@HiltAndroidTest
+ HiltAndroidRule
必须排在首位
@HiltAndroidTestHiltAndroidRulekotlin
@HiltAndroidTest
class HomeScreenTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) val composeRule = createAndroidComposeRule<MainActivity>()
@Inject lateinit var userRepository: UserRepository
@Before fun inject() = hiltRule.inject()
}HiltAndroidRule/hilt-testingHiltAndroidRuleorder@Rule(order = 0)order = 101order = -1order = 0/hilt-testing"You must annotate any UI test that uses Hilt with. This annotation is responsible for generating the Hilt components for each test. Also, you need to add the@HiltAndroidTestto the test class." —HiltAndroidRuledeveloper.android.com/training/dependency-injection/hilt-testing
"To inject types into a test, usefor field injection. To tell Hilt to populate the@Injectfields, call@Inject." —hiltRule.inject()developer.android.com/training/dependency-injection/hilt-testing
kotlin
@HiltAndroidTest
class HomeScreenTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) val composeRule = createAndroidComposeRule<MainActivity>()
@Inject lateinit var userRepository: UserRepository
@Before fun inject() = hiltRule.inject()
}HiltAndroidRule/hilt-testingHiltAndroidRuleorder@Rule(order = 0)order = 101order = 0order = -1order = 0/hilt-testing“任何使用 Hilt 的 UI test 都必须使用标注。该注解负责为每个测试生成 Hilt 组件。此外,还需要将@HiltAndroidTest添加到测试类中。” —HiltAndroidRuledeveloper.android.com/training/dependency-injection/hilt-testing
“要对测试中的类型进行注入,请使用执行字段注入。要让 Hilt 填充@Inject字段,请调用@Inject。” —hiltRule.inject()developer.android.com/training/dependency-injection/hilt-testing
@TestInstallIn
— replace a binding for ALL tests
@TestInstallIn@TestInstallIn
——为所有测试替换 binding
@TestInstallInkotlin
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [AnalyticsModule::class],
)
abstract class FakeAnalyticsModule {
@Singleton @Binds
abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
}The replacement applies to every in the module. Use this when the same fake fits every test (in-memory DB, no-op analytics).
@HiltAndroidTestkotlin
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [AnalyticsModule::class],
)
abstract class FakeAnalyticsModule {
@Singleton @Binds
abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
}该替换会应用于 module 中的每个 。当同一个 fake 适用于所有测试时,可采用这种方式(内存 DB、无操作 analytics)。
@HiltAndroidTest@UninstallModules
— replace in a SINGLE test
@UninstallModules@UninstallModules
——在单个测试中替换 binding
@UninstallModuleskotlin
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@Module @InstallIn(SingletonComponent::class)
abstract class TestModule {
@Singleton @Binds
abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
}
}Per warnings (must surface in skills):
/hilt-testing"Warning: You cannot uninstall modules that are not annotated with. Attempting to do so causes a compilation error."@InstallIn
"Warning:can only uninstall@UninstallModulesmodules, not@InstallInmodules." —@TestInstallIndeveloper.android.com/training/dependency-injection/hilt-testing
kotlin
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@Module @InstallIn(SingletonComponent::class)
abstract class TestModule {
@Singleton @Binds
abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
}
}根据 中的警告(skill 中必须呈现):
/hilt-testing“**警告:**无法卸载未使用标注的 module。尝试这样做会导致编译错误。”@InstallIn
“警告:只能卸载@UninstallModulesmodule,不能卸载@InstallInmodule。” —@TestInstallIndeveloper.android.com/training/dependency-injection/hilt-testing
@BindValue
— quick swap for a single test
@BindValue@BindValue
——在单个测试中快速替换 binding
@BindValuekotlin
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@BindValue @JvmField
val analyticsService: AnalyticsService = FakeAnalyticsService()
}@BindValuekotlin
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@BindValue @JvmField
val analyticsService: AnalyticsService = FakeAnalyticsService()
}@BindValue@CustomTestApplication
— non-Hilt base class
@CustomTestApplication@CustomTestApplication
——非 Hilt 基类
@CustomTestApplicationWhen the production extends a non-Hilt base (, a vendor app class), Hilt cannot generate the test app automatically. Use:
ApplicationMultiDexApplicationkotlin
@CustomTestApplication(BaseApplication::class)
interface HiltTestApplicationThe generated is then named in or via a custom .
HiltTestApplication_ApplicationtestInstrumentationRunnerArgumentsAndroidJUnitRunner当生产 继承自非 Hilt 基类(、某个厂商应用类)时,Hilt 无法自动生成测试 Application。可使用:
ApplicationMultiDexApplicationkotlin
@CustomTestApplication(BaseApplication::class)
interface HiltTestApplication随后在 中指定生成的 ,或通过自定义 进行配置。
testInstrumentationRunnerArgumentsHiltTestApplication_ApplicationAndroidJUnitRunnerRule ordering with multiple rules
组合多个 rule 时的顺序
kotlin
@HiltAndroidTest
class SettingsActivityTest {
@get:Rule(order = 0) var hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) var settingsActivityTestRule = SettingsActivityTestRule(...)
}—
developer.android.com/training/dependency-injection/hilt-testingOr with for mid-chain composition:
RuleChainkotlin
@get:Rule
val chain: TestRule = RuleChain
.outerRule(HiltAndroidRule(this))
.around(InstantTaskExecutorRule())
.around(MainDispatcherRule())kotlin
@HiltAndroidTest
class SettingsActivityTest {
@get:Rule(order = 0) var hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) var settingsActivityTestRule = SettingsActivityTestRule(...)
}—
developer.android.com/training/dependency-injection/hilt-testing也可以使用 在链条中间组合:
RuleChainkotlin
@get:Rule
val chain: TestRule = RuleChain
.outerRule(HiltAndroidRule(this))
.around(InstantTaskExecutorRule())
.around(MainDispatcherRule())Patterns
模式
Pattern: WRONG vs RIGHT — Given-When-Then comment block
模式:错误 vs 正确——Given-When-Then 注释块
kotlin
// WRONG — no structure; reader cannot find the act vs assert boundary
@Test
fun loadsUser() = runTest {
val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
val vm = UserViewModel(repo)
vm.load(UserId("u1"))
val state = vm.state.value
assertEquals("Alice", state.name)
assertFalse(state.isLoading)
}
// WRONG because: the test crams setup, action, and assertion together. With three or
// more lines per stage, readers cannot locate failures fast. Google's own samples use
// Given-When-Then comments as visual separators.kotlin
// RIGHT
@Test
fun loadUser_seededId_emitsLoadedState() = runTest {
// Given a fake repo seeded with Alice
val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
val vm = UserViewModel(repo)
// When loading the seeded id
vm.load(UserId("u1"))
// Then the state is Loaded with Alice
assertEquals(UserUiState.Loaded(name = "Alice"), vm.state.value)
}kotlin
// WRONG — no structure; reader cannot find the act vs assert boundary
@Test
fun loadsUser() = runTest {
val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
val vm = UserViewModel(repo)
vm.load(UserId("u1"))
val state = vm.state.value
assertEquals("Alice", state.name)
assertFalse(state.isLoading)
}
// WRONG because: the test crams setup, action, and assertion together. With three or
// more lines per stage, readers cannot locate failures fast. Google's own samples use
// Given-When-Then comments as visual separators.kotlin
// RIGHT
@Test
fun loadUser_seededId_emitsLoadedState() = runTest {
// Given a fake repo seeded with Alice
val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
val vm = UserViewModel(repo)
// When loading the seeded id
vm.load(UserId("u1"))
// Then the state is Loaded with Alice
assertEquals(UserUiState.Loaded(name = "Alice"), vm.state.value)
}Pattern: WRONG vs RIGHT — Hilt rule order
模式:错误 vs 正确——Hilt rule 顺序
kotlin
// WRONG
@HiltAndroidTest
class HomeScreenTest {
@get:Rule val composeRule = createAndroidComposeRule<MainActivity>() // order = 0 by default
@get:Rule val hiltRule = HiltAndroidRule(this)
}
// WRONG because: with no order, JUnit picks ordering implementation-defined. The
// Activity may launch before Hilt's component is built, throwing at @Inject sites.
// Per /hilt-testing, HiltAndroidRule must run first.kotlin
// RIGHT
@HiltAndroidTest
class HomeScreenTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) val composeRule = createAndroidComposeRule<MainActivity>()
}kotlin
// WRONG
@HiltAndroidTest
class HomeScreenTest {
@get:Rule val composeRule = createAndroidComposeRule<MainActivity>() // order = 0 by default
@get:Rule val hiltRule = HiltAndroidRule(this)
}
// WRONG because: with no order, JUnit picks ordering implementation-defined. The
// Activity may launch before Hilt's component is built, throwing at @Inject sites.
// Per /hilt-testing, HiltAndroidRule must run first.kotlin
// RIGHT
@HiltAndroidTest
class HomeScreenTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) val composeRule = createAndroidComposeRule<MainActivity>()
}Pattern: WRONG vs RIGHT — non-deterministic time
模式:错误 vs 正确——非确定性时间
kotlin
// WRONG
class DueDateTest {
@Test fun reportsOverdue() {
val task = Task(dueAt = Instant.now().minusSeconds(60))
assertTrue(task.isOverdue()) // depends on real wall clock; flake risk on slow CI
}
}kotlin
// RIGHT
class DueDateTest {
private val fixedNow = Instant.parse("2024-01-01T00:00:00Z")
private val clock = Clock.fixed(fixedNow, ZoneId.of("UTC"))
@Test fun reportsOverdue() {
val task = Task(dueAt = fixedNow.minusSeconds(60), clock = clock)
assertTrue(task.isOverdue())
}
}kotlin
// WRONG
class DueDateTest {
@Test fun reportsOverdue() {
val task = Task(dueAt = Instant.now().minusSeconds(60))
assertTrue(task.isOverdue()) // depends on real wall clock; flake risk on slow CI
}
}kotlin
// RIGHT
class DueDateTest {
private val fixedNow = Instant.parse("2024-01-01T00:00:00Z")
private val clock = Clock.fixed(fixedNow, ZoneId.of("UTC"))
@Test fun reportsOverdue() {
val task = Task(dueAt = fixedNow.minusSeconds(60), clock = clock)
assertTrue(task.isOverdue())
}
}Pattern: WRONG vs RIGHT — @BindValue
over every { }
@BindValueevery { }模式:错误 vs 正确——使用 @BindValue
,而不是 every { }
@BindValueevery { }kotlin
// WRONG — mocking a Hilt-injected real instance
@HiltAndroidTest
class SettingsActivityTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@Inject lateinit var analytics: AnalyticsService
@Test fun tracks() {
// analytics is the real production instance; tests now mutate prod state
every { (analytics as RealAnalyticsService).enabled = false } // does not compile
}
}kotlin
// RIGHT — replace at the binding boundary
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@BindValue @JvmField
val analytics: AnalyticsService = FakeAnalyticsService()
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
}kotlin
// WRONG — mocking a Hilt-injected real instance
@HiltAndroidTest
class SettingsActivityTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@Inject lateinit var analytics: AnalyticsService
@Test fun tracks() {
// analytics is the real production instance; tests now mutate prod state
every { (analytics as RealAnalyticsService).enabled = false } // does not compile
}
}kotlin
// RIGHT — replace at the binding boundary
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@BindValue @JvmField
val analytics: AnalyticsService = FakeAnalyticsService()
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
}Mandatory rules
强制规则
- MUST order to execute first when combined with any rule that touches the injected graph (Activity, Compose, Fragment, Coroutine). The conventional shape is
HiltAndroidRuleon Hilt and@Rule(order = 0)on the next rule, but any monotonic ordering that puts Hilt first is fine —@Rule(order = 1)says "the/hilt-testingexecutes first", not specificallyHiltAndroidRule.order = 0 - MUST call in
hiltRule.inject()for any test class with@Beforefields.@Inject - MUST NOT annotate a -replaced module with
@TestInstallIn— Hilt fails compilation per the page's warning box.@UninstallModules - MUST NOT attribute determinism guidance to . Use
/training/testing/fundamentals/strategies./training/testing/instrumented-tests/stability - MUST NOT claim "Google recommends Given-When-Then". The pages use it in samples; they do not prescribe it.
- MUST inject a (or equivalent time source),
Clock, andDispatcherProviderseed for any code whose output depends on them.Random - MUST name local tests with backticks freely; for instrumented tests that may run on devices below API 30, use (per
camelCase_state_expected: "Using backticks to name tests in Kotlin is only supported on devices running API 30 and above" — the gate is the runtime device API, not just the module's/instrumented-tests).minSdk - PREFERRED: Given-When-Then over Arrange-Act-Assert, mirroring the vocabulary in Google's own code samples.
- PREFERRED: for single-test binding swaps,
@BindValuefor module-wide swaps.@TestInstallIn - PREFERRED: disable animations via rather than per-test ADB shell calls.
testOptions.animationsDisabled = true
- 必须:将 安排在任何接触注入依赖图的 rule(Activity、Compose、Fragment、Coroutine)之前执行。惯用形式是在 Hilt 上使用
HiltAndroidRule,在下一个 rule 上使用@Rule(order = 0),但任何确保 Hilt 排在首位的单调顺序都可以——@Rule(order = 1)的要求是“/hilt-testingexecutes first”,而不是必须使用HiltAndroidRule。order = 0 - 必须:对于包含 字段的测试类,在
@Inject中调用@Before。hiltRule.inject() - 不得:对已被 替换的 module 使用
@TestInstallIn——根据该页面的警告框,Hilt 会编译失败。@UninstallModules - 不得:将确定性指导归到 。应使用
/training/testing/fundamentals/strategies。/training/testing/instrumented-tests/stability - 不得:声称“Google 推荐 Given-When-Then”。这些页面只在示例中使用该模式,并未明确推荐。
- 必须:对于输出依赖时间、调度器或随机性的代码,注入 (或等效时间源)、
Clock和DispatcherProviderseed。Random - 必须:可自由使用 backtick 命名 local test;对于可能运行在 API 30 以下设备上的 instrumented test,使用 。根据
camelCase_state_expected:“在 Kotlin 中使用 backtick 命名测试,仅受运行 API 30 及以上版本的设备支持”——限制条件是运行时设备 API,而不只是 module 的/instrumented-tests。minSdk - **推荐:**优先使用 Given-When-Then,而不是 Arrange-Act-Assert,以与 Google 自身代码示例中的术语保持一致。
- **推荐:**单次测试替换 binding 时使用 ;module 级替换时使用
@BindValue。@TestInstallIn - **推荐:**通过 禁用 animation,而不是在每个测试中调用 ADB shell。
testOptions.animationsDisabled = true
Verification
验证
- Every class declares
@HiltAndroidTestwith anHiltAndroidRulethat places it first relative to any other JUnit rules in the class (orderis the conventional choice).@Rule(order = 0) - Every class with
@HiltAndroidTestfields calls@InjectinhiltRule.inject().@Before - No production code references classes; all fakes live under
Fake*orsrc/androidTest/(or a dedicatedsrc/test/module).core-testing - No test method directly reads ,
Instant.now(), orSystem.currentTimeMillis()without a seed/injection.Random() - set in module
testOptions.animationsDisabled = true.build.gradle.kts - CI runs identically to local — no test relies on network, real time, or ambient device state.
- All tests in the module follow one structural convention (Given-When-Then OR Arrange-Act-Assert; not both).
- 每个 class 都声明了
@HiltAndroidTest,其HiltAndroidRule确保它相对于 class 中的其他 JUnit rule 最先执行(order是惯用选择)。@Rule(order = 0) - 每个包含 字段的
@Injectclass 都在@HiltAndroidTest中调用了@Before。hiltRule.inject() - 生产代码没有引用 class;所有 fake 均位于
Fake*或src/androidTest/下(或独立的src/test/module 中)。core-testing - 没有测试方法在未经 seed / 注入的情况下直接读取 、
Instant.now()或System.currentTimeMillis()。Random() - 已在 module 的 中设置
build.gradle.kts。testOptions.animationsDisabled = true - CI 与本地环境运行方式一致——没有测试依赖网络、真实时间或环境中的设备状态。
- module 中的所有测试遵循同一种结构约定(Given-When-Then 或 Arrange-Act-Assert,不能混用)。
References
参考资料
- — qualitative pyramid, network-access table per layer.
developer.android.com/training/testing/fundamentals/strategies - — hermetic-test definition (in passing).
developer.android.com/training/testing/fundamentals/test-doubles - — determinism / flake guidance (NOT on /strategies).
developer.android.com/training/testing/instrumented-tests/stability - — backtick naming caveat ("Using backticks ... only supported on devices running API 30 and above").
developer.android.com/training/testing/instrumented-tests - —
developer.android.com/training/dependency-injection/hilt-testing,@HiltAndroidTest,HiltAndroidRule,@TestInstallIn,@UninstallModules,@BindValue, the warning boxes, the rule-ordering example.@CustomTestApplication - — verbatim Hilt quotes and the source-of-truth map per page.
tasks/research/R8-android-fundamentals.md - CORPUS §G.3 — JUnit4 wrapper at
MainDispatcherRule.testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt - Sibling skills: ,
../../concepts/understanding-the-testing-pyramid/SKILL.md,../../concepts/choosing-what-to-test/SKILL.md,../../doubles/picking-test-doubles/SKILL.md.../organizing-test-source-sets/SKILL.md - Cross-category: ,
../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md,../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.md,../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md,../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md,../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md,../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md.../../../adb/observability/extracting-logs-with-logcat/SKILL.md
- ——定性测试金字塔、各层级的网络访问表。
developer.android.com/training/testing/fundamentals/strategies - ——hermetic test 定义(顺带提及)。
developer.android.com/training/testing/fundamentals/test-doubles - ——确定性 / flaky 指导(不在
developer.android.com/training/testing/instrumented-tests/stability上)。/strategies - ——backtick 命名注意事项(“在 Kotlin 中使用 backtick……仅受运行 API 30 及以上版本的设备支持”)。
developer.android.com/training/testing/instrumented-tests - ——
developer.android.com/training/dependency-injection/hilt-testing、@HiltAndroidTest、HiltAndroidRule、@TestInstallIn、@UninstallModules、@BindValue、警告框以及 rule 排序示例。@CustomTestApplication - ——Hilt 引文逐字记录,以及按页面划分的事实来源映射。
tasks/research/R8-android-fundamentals.md - CORPUS §G.3——JUnit4 wrapper,位于
MainDispatcherRule。testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt - 同级 skills:、
../../concepts/understanding-the-testing-pyramid/SKILL.md、../../concepts/choosing-what-to-test/SKILL.md、../../doubles/picking-test-doubles/SKILL.md。../organizing-test-source-sets/SKILL.md - 跨类别:、
../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md、../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.md、../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md、../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md、../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md、../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md。../../../adb/observability/extracting-logs-with-logcat/SKILL.md