choosing-what-to-test
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseChoosing What to Test — Cover State, Skip Framework Entry Points
选择要测试的内容——覆盖状态,跳过框架入口
Android test suites under-cover business logic and over-cover framework glue. Google's page sorts test value by what state the code touches and explicitly names the categories of tests to avoid. This skill encodes those categories and the edge-case checklist so the agent can advise concretely instead of saying "test everything important".
/training/testing/fundamentals/what-to-testAndroid 测试套件通常对业务逻辑覆盖不足,却过度覆盖框架粘合代码。Google 的 页面根据代码触及的状态类型划分测试价值,并明确指出应避免的测试类别。本 skill 将这些类别和边界情况检查清单系统化,让 agent 能够给出具体建议,而不是只说“测试所有重要内容”。
/training/testing/fundamentals/what-to-testWhen to use this skill
何时使用此 skill
- The user asks "what should I write tests for in this module" or "do I need a test for X".
- The user asks whether to unit-test an ,
Activity, orFragment(answer: usually no — see "What NOT to test").Service - The user is reviewing a PR and the test gap is unclear.
- The user asks "what edge cases am I missing for this function".
- The user asks where the testing effort should land between ViewModel, Repository, and Composable.
- 用户询问“应该为这个模块中的哪些内容编写测试”或“我需要为 X 编写测试吗”。
- 用户询问是否应该对 、
Activity或Fragment进行 unit test(答案通常是不要——参见“不应测试什么”)。Service - 用户正在审查 PR,但不清楚测试缺口在哪里。
- 用户询问“这个函数还遗漏了哪些边界情况”。
- 用户询问测试工作应该放在 ViewModel、Repository 和 Composable 之间哪个位置。
When NOT to use this skill
何时不应使用此 skill
- The user already knows what to test and is choosing the test scope (small/medium/big) — use .
../understanding-the-testing-pyramid/SKILL.md - The user is choosing between fakes / mocks / stubs — use .
../../doubles/picking-test-doubles/SKILL.md - The user is wiring source sets (vs
src/test/) — usesrc/androidTest/.../../strategies/organizing-test-source-sets/SKILL.md
- 用户已经知道要测试什么,正在选择测试范围(小 / 中 / 大)——请使用 。
../understanding-the-testing-pyramid/SKILL.md - 用户正在选择 fakes / mocks / stubs——请使用 。
../../doubles/picking-test-doubles/SKILL.md - 用户正在配置 source sets(与
src/test/)——请使用src/androidTest/。../../strategies/organizing-test-source-sets/SKILL.md
Prerequisites
前置条件
- A module with at least one , repository, or screen.
ViewModel - Familiarity with the Android architecture layers (UI / Domain / Data) so the agent can map "data layer" to a real path.
- The 3-layer pyramid framing from .
../understanding-the-testing-pyramid/SKILL.md
- 模块中至少包含一个 、repository 或 screen。
ViewModel - 熟悉 Android 架构层(UI / Domain / Data),以便 agent 能将“数据层”映射到真实路径。
- 熟悉 中的三层金字塔框架。
../understanding-the-testing-pyramid/SKILL.md
Five categories of state to cover
需要覆盖的五类状态
The five state categories below are the synthesis the user asked for. They map onto the verbatim sections of (the page itself uses layer-style headers — "Essential unit tests", "UI tests", "Testing Edge Cases" — but the underlying axis is what kind of state changes).
developer.android.com/training/testing/fundamentals/what-to-test下面五类状态是用户要求的综合归纳。它们与 中的原文小节一一对应(该页面本身使用层级式标题——“Essential unit tests”、“UI tests”、“Testing Edge Cases”——但其底层判断轴是哪类状态发生变化)。
developer.android.com/training/testing/fundamentals/what-to-test1. State on screen — what the user observes right now
1. 屏幕上的状态——用户当前可观察到的内容
What is rendered: a button label, a list count, an enabled/disabled state, a checkbox toggle. Tested via UI tests:
"Screen UI tests check critical user interactions in a single screen. They perform actions such as clicking on buttons, typing in forms, and checking visible states. One test class per screen is a good starting point." —developer.android.com/training/testing/fundamentals/what-to-test
"User flow tests or Navigation tests, covering most common paths. These tests simulate a user moving through a navigation flow." —developer.android.com/training/testing/fundamentals/what-to-test
For Compose: assert via / / . For Views: . Use the cross-category skill .
onNodeWithTag(...).assertIsDisplayed()assertTextEquals(...)assertIsEnabled()onView(...).check(matches(isDisplayed()))../../../instrumentation/espresso/writing-espresso-tests/SKILL.md界面所呈现的内容:按钮标签、列表数量、启用 / 禁用状态、复选框开关状态。通过 UI tests 验证:
“屏幕 UI 测试会检查单个屏幕中的关键用户交互。它们会执行点击按钮、在表单中输入以及检查可见状态等操作。每个屏幕设置一个测试类是一个不错的起点。” —developer.android.com/training/testing/fundamentals/what-to-test
“用户流程测试或导航测试覆盖最常见的路径。这些测试模拟用户完成导航流程的过程。” —developer.android.com/training/testing/fundamentals/what-to-test
对于 Compose:通过 / / 进行断言。对于 Views:使用 。请使用跨分类 skill 。
onNodeWithTag(...).assertIsDisplayed()assertTextEquals(...)assertIsEnabled()onView(...).check(matches(isDisplayed()))../../../instrumentation/espresso/writing-espresso-tests/SKILL.md2. State held in memory — ViewModel
and presenter state
ViewModel2. 内存中保存的状态——ViewModel
和 presenter 状态
ViewModelViewModel.uiState"Unit tests for ViewModels, or presenters." —developer.android.com/training/testing/fundamentals/what-to-test
A ViewModel test launches the ViewModel with a fake repository, drives an event, and asserts on the exposed / . See and .
StateFlowLiveData../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.mdViewModel.uiState“针对 ViewModels 或 presenters 的 unit tests。” —developer.android.com/training/testing/fundamentals/what-to-test
ViewModel 测试会使用 fake repository 启动 ViewModel、驱动一个事件,并对所暴露的 / 进行断言。请参阅 和 。
StateFlowLiveData../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.md3. Persisted state — DB, DataStore, SharedPreferences, files
3. 持久化状态——DB、DataStore、SharedPreferences、文件
What survives process death:
"Unit tests for the data layer, especially repositories. Most of the data layer should be platform-independent. Doing so enables test doubles to replace database modules and remote data sources in tests." —developer.android.com/training/testing/fundamentals/what-to-test
Two flavors:
- Repository unit tests — fake the storage source; verify the repository's caching, mapping, error handling.
- Storage integration tests — exercise Room / DataStore / SharedPreferences with their real implementations. These are small instrumented tests per ("Small instrumented test: You can verify that your code works well with a framework feature, such as a SQLite database").
/fundamentals
在进程终止后仍能保留的状态:
“针对数据层(尤其是 repositories)的 unit tests。数据层的大部分代码应当与平台无关。这样便可在测试中使用 test doubles 替换数据库模块和远程数据源。” —developer.android.com/training/testing/fundamentals/what-to-test
分为两种:
- Repository unit tests——fake 存储源;验证 repository 的缓存、映射和错误处理。
- Storage integration tests——使用真实实现测试 Room / DataStore / SharedPreferences。根据 ,这些是小型 instrumented tests(“小型 instrumented test:可以使用它验证代码是否能够与某个框架功能正确配合,例如 SQLite 数据库”)。
/fundamentals
4. Other state — system bars, system services, alarms, broadcasts
4. 其他状态——系统栏、系统服务、alarms、broadcasts
Window-insets state, dark-mode flag, alarm scheduling, background-job state. The page does not give this its own header but the page covers it under instrumented tests. Test via Robolectric (medium-local) when shadows exist, or instrumented tests when the real system is required.
/what-to-test/fundamentalsWindow-insets 状态、深色模式标志、alarm 调度、后台作业状态。 页面没有为这些内容设置独立标题,但 页面在 instrumented tests 部分涵盖了它们。如果存在对应的 shadow,可通过 Robolectric(medium-local)进行测试;需要真实系统时应使用 instrumented tests。
/what-to-test/fundamentals5. Errors and edge cases
5. 错误和边界情况
"Unit tests should focus on both normal and edge cases. Edge cases are uncommon scenarios that human testers and larger tests are unlikely to catch. Examples include the following:
- Math operations using negative numbers, zero, and boundary conditions.
- All the possible network connection errors.
- Corrupted data, such as malformed JSON.
- Simulating full storage when saving to a file.
- Object recreated in the middle of a process (such as an activity when the device is rotated)." —
developer.android.com/training/testing/fundamentals/what-to-test
This is the highest-value column in any test budget — humans miss these, big tests miss these, and a small fake-driven unit test catches them in 5 ms.
“Unit tests 应同时关注正常情况和边界情况。边界情况是人类测试人员和大型测试不太可能捕获的少见场景。例如:
- 使用负数、零和边界条件的数学运算。
- 所有可能的网络连接错误。
- 损坏的数据,例如格式错误的 JSON。
- 保存文件时模拟存储空间已满。
- 对象在进程运行过程中被重新创建,例如设备旋转时重新创建 activity。” —
developer.android.com/training/testing/fundamentals/what-to-test
这是任何测试预算中价值最高的一类——人类会遗漏这些情况,大型测试也会遗漏这些情况,而一个由 fake 驱动的小型 unit test 可以在 5 ms 内捕获它们。
What NOT to test (verbatim)
不应测试什么(原文)
The page is unusually direct here:
"Some unit tests should be avoided because of their low value:
- Tests that verify the correct operation of the framework or a library, not your code.
- Framework entry points such as activities, fragments, or services should not have business logic so unit testing shouldn't be a priority. Unit tests for activities have little value, because they would cover mostly framework code and they require a more involved setup. Instrumented tests such as UI tests can cover these classes." —
developer.android.com/training/testing/fundamentals/what-to-test
Operational consequences:
- MUST NOT write unit tests of an
Robolectric'sActivityto assert that views are inflated. That is testing the framework.onCreate - MUST NOT write a unit test of 's migration registration. That tests Room.
RoomDatabase.Builder - MUST NOT write a unit test that mocks to assert that
Retrofitpaths resolve. That tests Retrofit.@GET - MUST NOT test private implementation details that change every refactor. Test public observable behavior.
- PREFERRED: when a class is hard to unit-test, refactor business logic out of it (→
Activity→ViewModel→UseCase) — the page closes the loop with "With a testable app architecture, the code follows a structure that allows you to easily test different parts of it in isolation." (cited fromRepository)./fundamentals
The page also flags additional categories briefly:
"There are more specialized tests such as screenshot tests, performance tests, and monkey tests." —developer.android.com/training/testing/fundamentals/what-to-test
These are out of scope for the "what to test" decision but should be mentioned when the user asks about visual regressions or render correctness — see the cross-category skill .
../../../compose/audit/auditing-compose-test-suite/SKILL.md该页面在这里表达得非常直接:
“有些 unit tests 应避免,因为其价值较低:
- 验证 framework 或 library 是否正确运行,而不是验证你的代码的测试。
- 诸如 activities、fragments 或 services 等 framework entry points 不应包含业务逻辑,因此 unit testing 不应作为优先事项。Activity 的 unit tests 价值很低,因为它们主要覆盖 framework code,而且需要更复杂的 setup。诸如 UI tests 等 instrumented tests 可以覆盖这些类。” —
developer.android.com/training/testing/fundamentals/what-to-test
实际执行要求:
- 绝不应编写针对 的
Activity.onCreateunit test 来断言 views 是否已膨胀。这是在测试 framework。Robolectric - 绝不应编写用于断言 migration 注册行为的 unit test。这是在测试 Room。
RoomDatabase.Builder - 绝不应编写 mock 并断言
Retrofit路径是否能够解析的 unit test。这是在测试 Retrofit。@GET - 绝不应测试每次重构都会变化的私有实现细节。应测试公开的可观察行为。
- 优先做法:当某个类难以进行 unit test 时,应将业务逻辑从中抽离(→
Activity→ViewModel→UseCase)——该页面以如下内容呼应了这一点:“采用可测试的应用架构后,代码会形成一种结构,使你可以轻松地隔离测试其中的不同部分。”(引自Repository)。/fundamentals
该页面还简要提到了其他类别:
“还有一些更专门的测试,例如 screenshot tests、performance tests 和 monkey tests。” —developer.android.com/training/testing/fundamentals/what-to-test
这些内容超出了“测试什么”的决策范围,但当用户询问视觉回归或渲染正确性时应予说明——请参阅跨分类 skill 。
../../../compose/audit/auditing-compose-test-suite/SKILL.mdPatterns
模式
Pattern: WRONG vs RIGHT — testing an Activity instead of its ViewModel
模式:错误 vs 正确——测试 Activity,而不是它的 ViewModel
kotlin
// WRONG
@RunWith(AndroidJUnit4::class)
class CheckoutActivityTest {
@get:Rule val rule = ActivityScenarioRule(CheckoutActivity::class.java)
@Test fun whenTotalIsNegative_showsError() {
rule.scenario.onActivity { activity ->
activity.viewModel.applyCoupon("FREE_BEER_NEGATIVE_PRICE")
// assert on the activity's TextView contents
assertEquals("Error", activity.findViewById<TextView>(R.id.error).text)
}
}
}
// WRONG because: the test rebuilds the framework lifecycle, the Activity, the inflater,
// and the View graph just to assert business logic that lives in the ViewModel. Per
// /what-to-test: "Unit tests for activities have little value, because they would cover
// mostly framework code".kotlin
// RIGHT — small, JVM, sub-50 ms
class CheckoutViewModelTest {
@Test fun applyCoupon_negativePrice_emitsError() = runTest {
val vm = CheckoutViewModel(FakePricingRepository(allowNegative = true))
vm.applyCoupon("FREE_BEER_NEGATIVE_PRICE")
assertEquals(CheckoutUiState.Error("Negative total"), vm.uiState.value)
}
}The still gets a thin big-test (Espresso / Compose-test) that asserts the error string is rendered. The logic lives in the ViewModel test. Two layers, two responsibilities.
Activitykotlin
// WRONG
@RunWith(AndroidJUnit4::class)
class CheckoutActivityTest {
@get:Rule val rule = ActivityScenarioRule(CheckoutActivity::class.java)
@Test fun whenTotalIsNegative_showsError() {
rule.scenario.onActivity { activity ->
activity.viewModel.applyCoupon("FREE_BEER_NEGATIVE_PRICE")
// assert on the activity's TextView contents
assertEquals("Error", activity.findViewById<TextView>(R.id.error).text)
}
}
}
// WRONG because: the test rebuilds the framework lifecycle, the Activity, the inflater,
// and the View graph just to assert business logic that lives in the ViewModel. Per
// /what-to-test: "Unit tests for activities have little value, because they would cover
// mostly framework code".kotlin
// RIGHT — small, JVM, sub-50 ms
class CheckoutViewModelTest {
@Test fun applyCoupon_negativePrice_emitsError() = runTest {
val vm = CheckoutViewModel(FakePricingRepository(allowNegative = true))
vm.applyCoupon("FREE_BEER_NEGATIVE_PRICE")
assertEquals(CheckoutUiState.Error("Negative total"), vm.uiState.value)
}
}ActivityPattern: WRONG vs RIGHT — over-mocking a util class
模式:错误 vs 正确——过度 mock util 类
kotlin
// WRONG
class FormatDurationTest {
private val clock = mockk<Clock>()
private val locale = mockk<Locale>()
@Test fun formatsMinutesAndSeconds() {
every { clock.now() } returns Instant.parse("2024-01-01T00:01:30Z")
every { locale.language } returns "en"
assertEquals("1m 30s", formatDuration(90.seconds, clock, locale))
}
}
// WRONG because: this is a pure-function utility per /what-to-test ("Unit tests for
// utility classes such as string manipulation and math"). Mocks add ceremony with
// no value. Pass real values.kotlin
// RIGHT
class FormatDurationTest {
@Test fun formatsMinutesAndSeconds() {
assertEquals("1m 30s", formatDuration(90.seconds))
}
@Test fun handlesZero() {
assertEquals("0s", formatDuration(0.seconds))
}
@Test fun handlesHoursBoundary() {
assertEquals("1h 0m 0s", formatDuration(3600.seconds))
}
}kotlin
// WRONG
class FormatDurationTest {
private val clock = mockk<Clock>()
private val locale = mockk<Locale>()
@Test fun formatsMinutesAndSeconds() {
every { clock.now() } returns Instant.parse("2024-01-01T00:01:30Z")
every { locale.language } returns "en"
assertEquals("1m 30s", formatDuration(90.seconds, clock, locale))
}
}
// WRONG because: this is a pure-function utility per /what-to-test ("Unit tests for
// utility classes such as string manipulation and math"). Mocks add ceremony with
// no value. Pass real values.kotlin
// RIGHT
class FormatDurationTest {
@Test fun formatsMinutesAndSeconds() {
assertEquals("1m 30s", formatDuration(90.seconds))
}
@Test fun handlesZero() {
assertEquals("0s", formatDuration(0.seconds))
}
@Test fun handlesHoursBoundary() {
assertEquals("1h 0m 0s", formatDuration(3600.seconds))
}
}Pattern: WRONG vs RIGHT — skipping the edge cases checklist
模式:错误 vs 正确——跳过边界情况检查清单
kotlin
// WRONG — only the happy path
class ParseAmountTest {
@Test fun parsesValidAmount() = assertEquals(12.34, parseAmount("12.34"))
}kotlin
// RIGHT — edge cases per /what-to-test
class ParseAmountTest {
@Test fun parsesValidAmount() = assertEquals(12.34, parseAmount("12.34"))
@Test fun parsesZero() = assertEquals(0.0, parseAmount("0"))
@Test fun parsesNegative() = assertEquals(-5.0, parseAmount("-5"))
@Test fun parsesScientific() = assertEquals(1e6, parseAmount("1e6"))
@Test fun rejectsEmpty() = assertNull(parseAmount(""))
@Test fun rejectsMalformed() = assertNull(parseAmount("12.34.56"))
@Test fun rejectsLeadingWhitespace() = assertNull(parseAmount(" 12"))
@Test fun rejectsLocaleComma() = assertNull(parseAmount("12,34")) // German format
@Test fun handlesMaxDouble() = assertEquals(Double.MAX_VALUE, parseAmount("1.7976931348623157E308"))
}kotlin
// WRONG — only the happy path
class ParseAmountTest {
@Test fun parsesValidAmount() = assertEquals(12.34, parseAmount("12.34"))
}kotlin
// RIGHT — edge cases per /what-to-test
class ParseAmountTest {
@Test fun parsesValidAmount() = assertEquals(12.34, parseAmount("12.34"))
@Test fun parsesZero() = assertEquals(0.0, parseAmount("0"))
@Test fun parsesNegative() = assertEquals(-5.0, parseAmount("-5"))
@Test fun parsesScientific() = assertEquals(1e6, parseAmount("1e6"))
@Test fun rejectsEmpty() = assertNull(parseAmount(""))
@Test fun rejectsMalformed() = assertNull(parseAmount("12.34.56"))
@Test fun rejectsLeadingWhitespace() = assertNull(parseAmount(" 12"))
@Test fun rejectsLocaleComma() = assertNull(parseAmount("12,34")) // German format
@Test fun handlesMaxDouble() = assertEquals(Double.MAX_VALUE, parseAmount("1.7976931348623157E308"))
}Edge-case mining checklist
边界情况挖掘检查清单
Run this checklist before declaring a unit-test pass complete. Items map to the verbatim list on plus skydoves additions for Compose/coroutines code.
/training/testing/fundamentals/what-to-test- Numeric boundaries — zero, negative, ,
Int.MAX_VALUE,Long.MIN_VALUE,Double.NaN.Double.POSITIVE_INFINITY - Empty / single / many collections — ,
emptyList(), lists with thousands of items.listOf(x) - Null — every nullable input. Even if the type system would refuse, deserialization can produce nulls (Moshi / kotlinx-serialization with ).
coerceInputValues - Malformed strings — empty, whitespace-only, length-1, length-MAX, non-ASCII, RTL text, emoji, ZWJ sequences, surrogate pairs.
- Locale variation — German number format , Arabic digits
12,34, Turkish dotted-i.٠١٢ - Network errors — , HTTP 4xx, HTTP 5xx, malformed JSON, truncated stream, timeout.
IOException - Storage errors — disk-full, permission-denied, corrupt SQLite, encrypted preference.
- Process death / state restoration — "Object recreated in the middle of a process (such as an activity when the device is rotated)" per the page. Cover ,
rememberSaveable, Bundle-restore.SavedStateHandle - Concurrency — same operation from two coroutines, cancellation mid-flight, slow producer + fast consumer (use ).
kotlinx-coroutines-test - Time — DST transitions, leap seconds, midnight crossings, timezone changes, monotonic vs wall clock.
- Configuration changes — dark mode flip, locale change, font scale at 1.5x and 2.0x, RTL layout.
The first half is straight from Google's verbatim list; the second half is operational extension for modern Android.
在宣布 unit-test 工作完成之前,应运行此检查清单。前半部分直接对应 中的原文清单,后半部分则是 skydoves 针对 Compose / coroutines 代码的补充。
/training/testing/fundamentals/what-to-test- 数值边界——零、负数、、
Int.MAX_VALUE、Long.MIN_VALUE、Double.NaN。Double.POSITIVE_INFINITY - 空集合 / 单元素集合 / 多元素集合——、
emptyList()、包含数千个元素的列表。listOf(x) - Null——每个可空输入。即使类型系统会拒绝 null,反序列化仍可能产生 null(使用 的 Moshi / kotlinx-serialization)。
coerceInputValues - 格式错误的字符串——空字符串、仅含空白、长度为 1、长度为 MAX、非 ASCII、RTL 文本、emoji、ZWJ 序列、代理项对。
- Locale 差异——德语数字格式 、阿拉伯数字
12,34、土耳其语带点 i。٠١٢ - 网络错误——、HTTP 4xx、HTTP 5xx、格式错误的 JSON、截断的 stream、timeout。
IOException - 存储错误——磁盘已满、权限被拒、SQLite 损坏、加密的 preference。
- 进程终止 / 状态恢复——根据该页面:“对象在进程运行过程中被重新创建,例如设备旋转时重新创建 activity。”应覆盖 、
rememberSaveable和 Bundle 恢复。SavedStateHandle - 并发——两个 coroutines 同时执行相同操作、执行途中取消、慢速 producer 与快速 consumer(使用 )。
kotlinx-coroutines-test - 时间——DST 转换、闰秒、跨越午夜、时区变化、monotonic clock 与 wall clock。
- 配置变化——切换深色模式、locale 变化、1.5x 和 2.0x 字体缩放、RTL 布局。
Decision matrix — should this code have a test?
决策矩阵——这段代码是否应该编写测试?
What does the code touch? Test? Where?
-----------------------------------------------------------------------------
Pure function / utility (string, math, mapping) YES src/test/ (small)
ViewModel / presenter state YES src/test/ (small)
Repository / use case (fake the storage) YES src/test/ (small)
Real Room / DataStore YES src/androidTest/ (small instrumented)
Composable rendering of state YES src/androidTest/ or src/test/ (Robolectric)
Navigation flow (multi-screen) YES src/androidTest/ (big)
Activity onCreate / inflation logic NO framework code
Fragment onViewCreated wiring NO framework code
Service onStartCommand wiring NO framework code
Retrofit interface (annotation routing) NO library code
Hilt module declarations NO library code
Compose Modifier internals NO library code
Generated code NO generated
Private function with no public observable effect NO test the public callerWhat does the code touch? Test? Where?
-----------------------------------------------------------------------------
Pure function / utility (string, math, mapping) YES src/test/ (small)
ViewModel / presenter state YES src/test/ (small)
Repository / use case (fake the storage) YES src/test/ (small)
Real Room / DataStore YES src/androidTest/ (small instrumented)
Composable rendering of state YES src/androidTest/ or src/test/ (Robolectric)
Navigation flow (multi-screen) YES src/androidTest/ (big)
Activity onCreate / inflation logic NO framework code
Fragment onViewCreated wiring NO framework code
Service onStartCommand wiring NO framework code
Retrofit interface (annotation routing) NO library code
Hilt module declarations NO library code
Compose Modifier internals NO library code
Generated code NO generated
Private function with no public observable effect NO test the public callerMandatory rules
强制规则
- MUST test public observable behavior (state exposed by , return values of
ViewModel, rendered semantics) — never private internals.Repository - MUST NOT unit-test framework entry points (,
Activity,Fragment) for business logic; refactor the logic out instead. PerService: "framework entry points ... should not have business logic so unit testing shouldn't be a priority"./what-to-test - MUST cover edge cases from the verbatim list before merging: numeric boundaries, network errors, malformed data, full storage, process recreation.
- MUST NOT verify framework or third-party library behavior. "Tests that verify the correct operation of the framework or a library, not your code" is on the explicit avoid list.
- PREFERRED: keep one Compose / Espresso big-test per screen for "state on screen" coverage; lean on small ViewModel tests for everything else.
- PREFERRED: when a class resists testing, treat that as an architecture signal — the production code is doing too many things or holds state in the wrong layer.
- 必须测试公开的可观察行为(暴露的状态、
ViewModel的返回值、已呈现的语义)——绝不测试私有内部实现。Repository - 绝不应为了测试业务逻辑而对 framework entry points(、
Activity、Fragment)进行 unit test;应将逻辑抽离。根据Service:“framework entry points 不应包含业务逻辑,因此 unit testing 不应作为优先事项。”/what-to-test - 必须在合并前覆盖原文清单中的边界情况:数值边界、网络错误、格式错误的数据、存储空间已满、进程重新创建。
- 绝不应验证 framework 或第三方 library 的行为。“验证 framework 或 library 是否正确运行,而不是验证你的代码的测试”明确列在应避免的清单中。
- 优先做法:每个 screen 保留一个用于覆盖“屏幕上的状态”的 Compose / Espresso big-test;其余内容尽量使用小型 ViewModel tests。
- 优先做法:当某个类难以测试时,应将其视为架构信号——生产代码可能承担了过多职责,或者将状态放在了错误的层中。
Verification
验证
- Every public function on every and
ViewModelin the module has at least one small test.Repository - Every screen has at least one big or medium test asserting "state on screen" via /
assertIsDisplayed.check(matches(isDisplayed())) - No test class targets only an /
Activity/Fragmentto assert framework-handled behavior.Service - The edge-case checklist above is reviewed for every new public function with non-trivial input domain.
- No test mocks ,
Retrofit,Room, orHiltinternals to verify their behavior.Compose - PR template (or review checklist) requires "what state does this code touch" to be answered before merge.
- 模块中每个 和
ViewModel的每个公开函数至少有一个小型测试。Repository - 每个 screen 至少有一个大型或中型测试,通过 /
assertIsDisplayed断言“屏幕上的状态”。check(matches(isDisplayed())) - 没有测试类仅针对 /
Activity/Fragment来断言由 framework 处理的行为。Service - 对于每个输入域较复杂的新公开函数,都已审查上述边界情况检查清单。
- 没有测试 mock 、
Retrofit、Room或Hilt的内部实现来验证它们的行为。Compose - PR 模板(或审查检查清单)要求在合并前回答“这段代码触及了什么状态”。
References
参考资料
- — the canonical source for every quote in this skill.
developer.android.com/training/testing/fundamentals/what-to-test - — testable architecture rationale, "Not all unit tests are local" quote.
developer.android.com/training/testing/fundamentals - — "Caution: Complex mocks should be avoided. Instead, you can use different types of test doubles such as fakes".
developer.android.com/training/testing/local-tests - — when state-on-screen tests must be instrumented vs Robolectric.
developer.android.com/training/testing/instrumented-tests - — verbatim "Essential unit tests" / "Testing Edge Cases" / "Unit Tests to Avoid" excerpts.
tasks/research/R8-android-fundamentals.md - Sibling skills: ,
../understanding-the-testing-pyramid/SKILL.md,../../doubles/picking-test-doubles/SKILL.md,../../strategies/applying-testing-strategies/SKILL.md.../../strategies/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/mocking/mocking-with-mockito/SKILL.md,../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md,../../../instrumentation/espresso/writing-espresso-tests/SKILL.md,../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md,../../../instrumentation/scenarios/launching-fragments-with-fragmentscenario/SKILL.md.../../../compose/audit/auditing-compose-test-suite/SKILL.md
- ——本 skill 中所有引文的权威来源。
developer.android.com/training/testing/fundamentals/what-to-test - ——可测试架构原理,以及“并非所有 unit tests 都是 local tests”的引文。
developer.android.com/training/testing/fundamentals - ——“注意:应避免复杂的 mocks,而应使用不同类型的 test doubles,例如 fakes”。
developer.android.com/training/testing/local-tests - ——何时 state-on-screen tests 必须使用 instrumented tests 而不是 Robolectric。
developer.android.com/training/testing/instrumented-tests - ——“Essential unit tests” / “Testing Edge Cases” / “Unit Tests to Avoid”的原文摘录。
tasks/research/R8-android-fundamentals.md - 同级 skills:、
../understanding-the-testing-pyramid/SKILL.md、../../doubles/picking-test-doubles/SKILL.md、../../strategies/applying-testing-strategies/SKILL.md。../../strategies/organizing-test-source-sets/SKILL.md - 跨分类 skills:、
../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md、../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.md、../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md、../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md、../../../instrumentation/espresso/writing-espresso-tests/SKILL.md、../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md、../../../instrumentation/scenarios/launching-fragments-with-fragmentscenario/SKILL.md。../../../compose/audit/auditing-compose-test-suite/SKILL.md