applying-testing-strategies

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Applying 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
    ,
    @BindValue
    , or rule ordering.
  • 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
    RuleChain.outerRule
    for combining
    HiltAndroidRule
    with
    ActivityScenarioRule
    or
    composeTestRule
    .
  • 用户询问“应该如何组织 Android 测试” / “Given-When-Then 还是 Arrange-Act-Assert” / “如何命名测试方法”。
  • 用户询问
    @HiltAndroidTest
    、
    HiltAndroidRule
    、
    @TestInstallIn
    、
    @UninstallModules
    、
    @BindValue
    或 rule 顺序。
  • 用户反馈“测试本地通过但在 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:
    dagger.hilt.android.testing.HiltAndroidRule
    and
    dagger.hilt.android.testing.HiltAndroidTest
    available on
    androidTestImplementation
    .
  • For determinism:
    kotlinx-coroutines-test
    ,
    Robolectric
    (if host tests), and the ability to stub
    System.currentTimeMillis()
    /
    Clock.systemDefaultZone()
    .
  • 熟悉
    ../../concepts/understanding-the-testing-pyramid/SKILL.md
    中的 small/medium/big 测试金字塔框架。
  • 具备一个注入了依赖项的测试目标(Hilt、手动 constructor injection 或其他 DI library)。
  • 对于 Hilt 部分:可通过
    androidTestImplementation
    使用
    dagger.hilt.android.testing.HiltAndroidRule
    和
    dagger.hilt.android.testing.HiltAndroidTest
    。
  • 对于确定性:
    kotlinx-coroutines-test
    、
    Robolectric
    (用于 host test),以及 stub
    System.currentTimeMillis()
    /
    Clock.systemDefaultZone()
    的能力。

Source-of-truth map (which page says what)

事实来源映射(哪个页面说明了什么)

Per
tasks/research/R8-android-fundamentals.md
, the strategy concepts live on three different pages. Naming the source matters because PR reviewers cite skills.
ConceptPage that actually documents it
Qualitative pyramid ("many small, few big")
/training/testing/fundamentals/strategies
Five-level Unit/Component/Feature/Application/RC table
/training/testing/fundamentals/strategies
Network access per layer
/training/testing/fundamentals/strategies
Determinism / flake handling
/training/testing/instrumented-tests/stability
(NOT /strategies)
Hermetic test definition
/training/testing/fundamentals/test-doubles
(in passing)
Given-When-Then comment styleNEVER named on any page; only used in code samples
Arrange-Act-AssertNEVER named on any page
Test namingOnly the backtick caveat on
/training/testing/instrumented-tests
@HiltAndroidTest
,
HiltAndroidRule
,
@TestInstallIn
,
@UninstallModules
,
@BindValue
/training/dependency-injection/hilt-testing
MUST NOT attribute determinism guidance to
/strategies
— it is on
/instrumented-tests/stability
. MUST NOT claim Google "recommends Given-When-Then" — the pages do not say that; they only use the comment style in samples.
根据
tasks/research/R8-android-fundamentals.md
,这些策略概念分布在三个不同页面上。说明来源很重要,因为 PR 评审者会引用 skills。
概念实际记录该内容的页面
定性测试金字塔(“大量小测试,少量大测试”)
/training/testing/fundamentals/strategies
五级 Unit/Component/Feature/Application/RC 表
/training/testing/fundamentals/strategies
各层级的网络访问
/training/testing/fundamentals/strategies
确定性 / flaky 处理
/training/testing/instrumented-tests/stability
(不是
/strategies
)
Hermetic test 定义
/training/testing/fundamentals/test-doubles
(顺带提及)
Given-When-Then 注释风格任何页面都未明确命名;仅在代码示例中使用
Arrange-Act-Assert任何页面都未明确命名
测试命名仅
/training/testing/instrumented-tests
中的 backtick 注意事项
@HiltAndroidTest
、
HiltAndroidRule
、
@TestInstallIn
、
@UninstallModules
、
@BindValue
/training/dependency-injection/hilt-testing
不得将确定性指导归到
/strategies
——它位于
/instrumented-tests/stability
。不得声称 Google “推荐 Given-When-Then”——这些页面并未这样表述;它们只在示例中使用这种注释风格。

Determinism

确定性

Per
/training/testing/instrumented-tests/stability
(and CORPUS §C "Common gotchas"), four sources of non-determinism dominate:
  1. Time —
    System.currentTimeMillis()
    ,
    Clock.systemDefaultZone()
    ,
    Instant.now()
    . Inject a
    Clock
    or use
    kotlinx-coroutines-test
    's virtual time.
  2. Concurrency / coroutines — direct
    Dispatchers.IO
    ,
    runBlocking
    , real
    delay
    . Use
    runTest
    , inject
    CoroutineDispatcher
    , replace
    Dispatchers.Main
    via
    Dispatchers.setMain(dispatcher)
    . See
    ../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md
    .
  3. Animation / frame timing — Compose's
    MainTestClock
    , View animations. Disable via
    testOptions.animationsDisabled = true
    (Gradle) or
    Settings.Global.WINDOW_ANIMATION_SCALE = 0
    (ADB). For Compose:
    mainClock.autoAdvance = false
    per the skydoves directives in
    docs/SPEC.md
    §5.
  4. External state — network, real DB,
    Random()
    ,
    UUID.randomUUID()
    . Inject seeds, use fakes, run
    pm clear
    before each instrumented test.
Concrete checklist:
  • Clock
    (or equivalent time source) is injected; tests substitute
    Clock.fixed(Instant.parse(...), ZoneId.of("UTC"))
    .
  • Dispatchers
    are injected via a
    DispatcherProvider
    interface or replaced with
    Dispatchers.setMain(StandardTestDispatcher())
    in a
    @Before
    .
  • Random
    is seeded (
    Random(42)
    ) or wrapped behind a
    RandomProvider
    that the test substitutes.
  • testOptions.animationsDisabled = true
    is set in
    build.gradle.kts
    .
  • CI runs
    pm clear <pkg>
    before every instrumented test (Test Orchestrator does this automatically; otherwise add an
    @Before
    ).
根据
/training/testing/instrumented-tests/stability
(以及 CORPUS §C“常见陷阱”),以下四类非确定性来源占主导:
  1. Time——
    System.currentTimeMillis()
    、
    Clock.systemDefaultZone()
    、
    Instant.now()
    。应注入
    Clock
    ,或使用
    kotlinx-coroutines-test
    的 virtual time。
  2. Concurrency / coroutines——直接使用
    Dispatchers.IO
    、
    runBlocking
    、真实的
    delay
    。应使用
    runTest
    、注入
    CoroutineDispatcher
    ,或通过
    Dispatchers.setMain(dispatcher)
    替换
    Dispatchers.Main
    。参见
    ../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md
    。
  3. Animation / frame timing——Compose 的
    MainTestClock
    、View animation。可通过
    testOptions.animationsDisabled = true
    (Gradle)或
    Settings.Global.WINDOW_ANIMATION_SCALE = 0
    (ADB)禁用。对于 Compose,应按照
    docs/SPEC.md
    §5 中的 skydoves 指令设置
    mainClock.autoAdvance = false
    。
  4. External state——网络、真实 DB、
    Random()
    、
    UUID.randomUUID()
    。应注入 seed、使用 fake,并在每次 instrumented test 前运行
    pm clear
    。
具体检查清单:
  • 已注入
    Clock
    (或等效的时间源);测试使用
    Clock.fixed(Instant.parse(...), ZoneId.of("UTC"))
    进行替换。
  • 通过
    DispatcherProvider
    interface 注入
    Dispatchers
    ,或在
    @Before
    中使用
    Dispatchers.setMain(StandardTestDispatcher())
    进行替换。
  • 已为
    Random
    设置 seed(
    Random(42)
    ),或将其封装在测试可替换的
    RandomProvider
    后面。
  • 已在
    build.gradle.kts
    中设置
    testOptions.animationsDisabled = true
    。
  • CI 在每次 instrumented test 前运行
    pm clear <pkg>
    (Test Orchestrator 会自动执行;否则需添加
    @Before
    )。

Hermetic vs integration

Hermetic 与 integration

The
/strategies
page does NOT formalize "hermetic" as a top-level term. The closest definition is on
/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
:
LayerNetwork access
UnitNone
ComponentNone
Feature"supports mocked network access"
Applicationn/a
Release Candidaten/a
MUST NOT present "hermetic" as if it were a dedicated section on
/strategies
— it is mentioned in passing on
/test-doubles
only. MUST cite both pages when discussing hermeticity:
/test-doubles
for the term,
/strategies
for the operational rule.
/strategies
页面并未将“hermetic”正式确立为顶层术语。最接近的定义位于
/test-doubles
:
“Hermetic test 会避开所有外部依赖,例如从互联网获取数据。” —
developer.android.com/training/testing/fundamentals/test-doubles
可操作的规则位于
/strategies
:
层级网络访问
Unit无
Component无
Feature“支持 mocked 网络访问”
Application不适用
Release Candidate不适用
不得将“hermetic”描述为
/strategies
上的独立章节——它只在
/test-doubles
中被顺带提及。讨论 hermeticity 时,必须同时引用两个页面:
/test-doubles
用于术语定义,
/strategies
用于可操作的规则。

Given-When-Then / Arrange-Act-Assert

Given-When-Then / Arrange-Act-Assert

Neither pattern is named on any of the four primary pages (
/fundamentals
,
/what-to-test
,
/test-doubles
,
/strategies
). They are visibly used in Google's code samples. From
/fundamentals
:
kotlin
// 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)
—
developer.android.com/training/testing/fundamentals
(Local/host-side unit test example)
And 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()))
—
developer.android.com/training/testing/fundamentals
(Espresso example)
Cite "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 interaction
Pick one vocabulary per repo (skydoves preference: Given-When-Then, matching Google's samples). Use it as inline comment blocks, not as method names.
这两种模式都没有在四个主要页面(
/fundamentals
、
/what-to-test
、
/test-doubles
、
/strategies
)中被明确命名,但它们在 Google 的代码示例中清晰可见。以下内容来自
/fundamentals
:
kotlin
// 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)
—
developer.android.com/training/testing/fundamentals
(Local/host-side 单元测试示例)
同一页面中的另一个示例:
kotlin
// When the Continue button is clicked
onView(withText("Continue")).perform(click())
// Then the Welcome screen is displayed
onView(withText("Welcome")).check(matches(isDisplayed()))
—
developer.android.com/training/testing/fundamentals
(Espresso 示例)
可以说“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 (
    src/test/
    ) — backtick names are safe (run on JVM, not the Android runtime).
  • Instrumented tests (
    src/androidTest/
    ) — backtick names require
    minSdk >= 30
    on the test APK. Below that, use
    camelCase
    or
    snake_case_with_underscores
    .
skydoves convention (combine these two facts): a
methodName_state_expected
shape that reads as a sentence.
loadUsers_emptyList_emitsEmptyState
applyCoupon_negativeTotal_emitsError
save_orchestratorMarksDirtyOnce
四个主要页面中唯一逐字给出的命名指导,是
/instrumented-tests
中的 backtick 注意事项:
“**注意:**在 Kotlin 中使用 backtick 命名测试,仅受运行 API 30 及以上版本的设备支持。” —
developer.android.com/training/testing/instrumented-tests
这意味着:
  • Local test(
    src/test/
    )——可安全使用 backtick 名称(运行于 JVM,而非 Android runtime)。
  • Instrumented test(
    src/androidTest/
    )——backtick 名称要求测试 APK 的
    minSdk >= 30
    。低于该版本时,使用
    camelCase
    或
    snake_case_with_underscores
    。
skydoves 约定(结合上述两项事实):采用
methodName_state_expected
格式,使其读起来像一句完整的话。
loadUsers_emptyList_emitsEmptyState
applyCoupon_negativeTotal_emitsError
save_orchestratorMarksDirtyOnce

Hilt for testing — the full mechanic

Hilt 测试的完整机制

Source:
developer.android.com/training/dependency-injection/hilt-testing
plus CORPUS §F.6.
来源:
developer.android.com/training/dependency-injection/hilt-testing
,以及 CORPUS §F.6。

Why 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

@HiltAndroidTest
+
HiltAndroidRule
必须排在首位

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
MUST execute before any rule that touches the injected graph (Activity launch, Compose setup). The
/hilt-testing
page phrases this as "the
HiltAndroidRule
executes first". Lower
order
values run first in JUnit4 (
@Rule(order = 0)
outranks
order = 1
), so the conventional pattern is
0
then
1
as shown — but the rule is "Hilt first", not specifically "order = 0". Negative numbers also work (
order = -1
paired with
order = 0
), and any monotonically increasing scheme is fine. Per
/hilt-testing
:
"You must annotate any UI test that uses Hilt with
@HiltAndroidTest
. This annotation is responsible for generating the Hilt components for each test. Also, you need to add the
HiltAndroidRule
to the test class." —
developer.android.com/training/dependency-injection/hilt-testing
"To inject types into a test, use
@Inject
for field injection. To tell Hilt to populate the
@Inject
fields, call
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
必须在任何接触注入依赖图的 rule(Activity 启动、Compose 初始化)之前执行。
/hilt-testing
页面将其表述为“
HiltAndroidRule
executes first”。在 JUnit4 中,较低的
order
值会先运行(
@Rule(order = 0)
优先于
order = 1
),因此惯用写法是像示例中那样使用
0
然后
1
——但规则是“Hilt first”,而不是必须使用
order = 0
。负数也有效(
order = -1
搭配
order = 0
),任何单调递增且确保 Hilt 在前的方案都可以。根据
/hilt-testing
:
“任何使用 Hilt 的 UI test 都必须使用
@HiltAndroidTest
标注。该注解负责为每个测试生成 Hilt 组件。此外,还需要将
HiltAndroidRule
添加到测试类中。” —
developer.android.com/training/dependency-injection/hilt-testing
“要对测试中的类型进行注入,请使用
@Inject
执行字段注入。要让 Hilt 填充
@Inject
字段,请调用
hiltRule.inject()
。” —
developer.android.com/training/dependency-injection/hilt-testing

@TestInstallIn
— replace a binding for ALL tests

@TestInstallIn
——为所有测试替换 binding

kotlin
@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [AnalyticsModule::class],
)
abstract class FakeAnalyticsModule {
    @Singleton @Binds
    abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
}
The replacement applies to every
@HiltAndroidTest
in the module. Use this when the same fake fits every test (in-memory DB, no-op analytics).
kotlin
@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [AnalyticsModule::class],
)
abstract class FakeAnalyticsModule {
    @Singleton @Binds
    abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
}
该替换会应用于 module 中的每个
@HiltAndroidTest
。当同一个 fake 适用于所有测试时,可采用这种方式(内存 DB、无操作 analytics)。

@UninstallModules
— replace in a SINGLE test

@UninstallModules
——在单个测试中替换 binding

kotlin
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
    @Module @InstallIn(SingletonComponent::class)
    abstract class TestModule {
        @Singleton @Binds
        abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
    }
}
Per
/hilt-testing
warnings (must surface in skills):
"Warning: You cannot uninstall modules that are not annotated with
@InstallIn
. Attempting to do so causes a compilation error."
"Warning:
@UninstallModules
can only uninstall
@InstallIn
modules, not
@TestInstallIn
modules." —
developer.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
    }
}
根据
/hilt-testing
中的警告(skill 中必须呈现):
“**警告:**无法卸载未使用
@InstallIn
标注的 module。尝试这样做会导致编译错误。”
“警告:
@UninstallModules
只能卸载
@InstallIn
module,不能卸载
@TestInstallIn
module。” —
developer.android.com/training/dependency-injection/hilt-testing

@BindValue
— quick swap for a single test

@BindValue
——在单个测试中快速替换 binding

kotlin
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
    @BindValue @JvmField
    val analyticsService: AnalyticsService = FakeAnalyticsService()
}
@BindValue
is the lightweight form — no test module class. Use when the test wants to seed a single instance and assert on it.
kotlin
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
    @BindValue @JvmField
    val analyticsService: AnalyticsService = FakeAnalyticsService()
}
@BindValue
是轻量形式——不需要 test module class。当测试需要注入单个实例并对其执行断言时,可使用这种方式。

@CustomTestApplication
— non-Hilt base class

@CustomTestApplication
——非 Hilt 基类

When the production
Application
extends a non-Hilt base (
MultiDexApplication
, a vendor app class), Hilt cannot generate the test app automatically. Use:
kotlin
@CustomTestApplication(BaseApplication::class)
interface HiltTestApplication
The generated
HiltTestApplication_Application
is then named in
testInstrumentationRunnerArguments
or via a custom
AndroidJUnitRunner
.
当生产
Application
继承自非 Hilt 基类(
MultiDexApplication
、某个厂商应用类)时,Hilt 无法自动生成测试 Application。可使用:
kotlin
@CustomTestApplication(BaseApplication::class)
interface HiltTestApplication
随后在
testInstrumentationRunnerArguments
中指定生成的
HiltTestApplication_Application
,或通过自定义
AndroidJUnitRunner
进行配置。

Rule 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-testing
Or with
RuleChain
for mid-chain composition:
kotlin
@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
也可以使用
RuleChain
在链条中间组合:
kotlin
@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 { }

模式:错误 vs 正确——使用
@BindValue
,而不是
every { }

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
    HiltAndroidRule
    to execute first when combined with any rule that touches the injected graph (Activity, Compose, Fragment, Coroutine). The conventional shape is
    @Rule(order = 0)
    on Hilt and
    @Rule(order = 1)
    on the next rule, but any monotonic ordering that puts Hilt first is fine —
    /hilt-testing
    says "the
    HiltAndroidRule
    executes first", not specifically
    order = 0
    .
  • MUST call
    hiltRule.inject()
    in
    @Before
    for any test class with
    @Inject
    fields.
  • MUST NOT annotate a
    @TestInstallIn
    -replaced module with
    @UninstallModules
    — Hilt fails compilation per the page's warning box.
  • MUST NOT attribute determinism guidance to
    /training/testing/fundamentals/strategies
    . Use
    /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
    Clock
    (or equivalent time source),
    DispatcherProvider
    , and
    Random
    seed for any code whose output depends on them.
  • MUST name local tests with backticks freely; for instrumented tests that may run on devices below API 30, use
    camelCase_state_expected
    (per
    /instrumented-tests
    : "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
    minSdk
    ).
  • PREFERRED: Given-When-Then over Arrange-Act-Assert, mirroring the vocabulary in Google's own code samples.
  • PREFERRED:
    @BindValue
    for single-test binding swaps,
    @TestInstallIn
    for module-wide swaps.
  • PREFERRED: disable animations via
    testOptions.animationsDisabled = true
    rather than per-test ADB shell calls.
  • 必须:将
    HiltAndroidRule
    安排在任何接触注入依赖图的 rule(Activity、Compose、Fragment、Coroutine)之前执行。惯用形式是在 Hilt 上使用
    @Rule(order = 0)
    ,在下一个 rule 上使用
    @Rule(order = 1)
    ,但任何确保 Hilt 排在首位的单调顺序都可以——
    /hilt-testing
    的要求是“
    HiltAndroidRule
    executes first”,而不是必须使用
    order = 0
    。
  • 必须:对于包含
    @Inject
    字段的测试类,在
    @Before
    中调用
    hiltRule.inject()
    。
  • 不得:对已被
    @TestInstallIn
    替换的 module 使用
    @UninstallModules
    ——根据该页面的警告框,Hilt 会编译失败。
  • 不得:将确定性指导归到
    /training/testing/fundamentals/strategies
    。应使用
    /training/testing/instrumented-tests/stability
    。
  • 不得:声称“Google 推荐 Given-When-Then”。这些页面只在示例中使用该模式,并未明确推荐。
  • 必须:对于输出依赖时间、调度器或随机性的代码,注入
    Clock
    (或等效时间源)、
    DispatcherProvider
    和
    Random
    seed。
  • 必须:可自由使用 backtick 命名 local test;对于可能运行在 API 30 以下设备上的 instrumented test,使用
    camelCase_state_expected
    。根据
    /instrumented-tests
    :“在 Kotlin 中使用 backtick 命名测试,仅受运行 API 30 及以上版本的设备支持”——限制条件是运行时设备 API,而不只是 module 的
    minSdk
    。
  • **推荐:**优先使用 Given-When-Then,而不是 Arrange-Act-Assert,以与 Google 自身代码示例中的术语保持一致。
  • **推荐:**单次测试替换 binding 时使用
    @BindValue
    ;module 级替换时使用
    @TestInstallIn
    。
  • **推荐:**通过
    testOptions.animationsDisabled = true
    禁用 animation,而不是在每个测试中调用 ADB shell。

Verification

验证

  • Every
    @HiltAndroidTest
    class declares
    HiltAndroidRule
    with an
    order
    that places it first relative to any other JUnit rules in the class (
    @Rule(order = 0)
    is the conventional choice).
  • Every
    @HiltAndroidTest
    class with
    @Inject
    fields calls
    hiltRule.inject()
    in
    @Before
    .
  • No production code references
    Fake*
    classes; all fakes live under
    src/androidTest/
    or
    src/test/
    (or a dedicated
    core-testing
    module).
  • No test method directly reads
    Instant.now()
    ,
    System.currentTimeMillis()
    , or
    Random()
    without a seed/injection.
  • testOptions.animationsDisabled = true
    set in module
    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).
  • 每个
    @HiltAndroidTest
    class 都声明了
    HiltAndroidRule
    ,其
    order
    确保它相对于 class 中的其他 JUnit rule 最先执行(
    @Rule(order = 0)
    是惯用选择)。
  • 每个包含
    @Inject
    字段的
    @HiltAndroidTest
    class 都在
    @Before
    中调用了
    hiltRule.inject()
    。
  • 生产代码没有引用
    Fake*
    class;所有 fake 均位于
    src/androidTest/
    或
    src/test/
    下(或独立的
    core-testing
    module 中)。
  • 没有测试方法在未经 seed / 注入的情况下直接读取
    Instant.now()
    、
    System.currentTimeMillis()
    或
    Random()
    。
  • 已在 module 的
    build.gradle.kts
    中设置
    testOptions.animationsDisabled = true
    。
  • CI 与本地环境运行方式一致——没有测试依赖网络、真实时间或环境中的设备状态。
  • module 中的所有测试遵循同一种结构约定(Given-When-Then 或 Arrange-Act-Assert,不能混用)。

References

参考资料

  • developer.android.com/training/testing/fundamentals/strategies
    — qualitative pyramid, network-access table per layer.
  • developer.android.com/training/testing/fundamentals/test-doubles
    — hermetic-test definition (in passing).
  • developer.android.com/training/testing/instrumented-tests/stability
    — determinism / flake guidance (NOT on /strategies).
  • developer.android.com/training/testing/instrumented-tests
    — backtick naming caveat ("Using backticks ... only supported on devices running API 30 and above").
  • developer.android.com/training/dependency-injection/hilt-testing
    —
    @HiltAndroidTest
    ,
    HiltAndroidRule
    ,
    @TestInstallIn
    ,
    @UninstallModules
    ,
    @BindValue
    ,
    @CustomTestApplication
    , the warning boxes, the rule-ordering example.
  • tasks/research/R8-android-fundamentals.md
    — verbatim Hilt quotes and the source-of-truth map per page.
  • CORPUS §G.3 —
    MainDispatcherRule
    JUnit4 wrapper at
    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
    ——定性测试金字塔、各层级的网络访问表。
  • developer.android.com/training/testing/fundamentals/test-doubles
    ——hermetic test 定义(顺带提及)。
  • developer.android.com/training/testing/instrumented-tests/stability
    ——确定性 / flaky 指导(不在
    /strategies
    上)。
  • developer.android.com/training/testing/instrumented-tests
    ——backtick 命名注意事项(“在 Kotlin 中使用 backtick……仅受运行 API 30 及以上版本的设备支持”)。
  • developer.android.com/training/dependency-injection/hilt-testing
    ——
    @HiltAndroidTest
    、
    HiltAndroidRule
    、
    @TestInstallIn
    、
    @UninstallModules
    、
    @BindValue
    、
    @CustomTestApplication
    、警告框以及 rule 排序示例。
  • tasks/research/R8-android-fundamentals.md
    ——Hilt 引文逐字记录,以及按页面划分的事实来源映射。
  • CORPUS §G.3——
    MainDispatcherRule
    JUnit4 wrapper,位于
    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
    。