organizing-test-source-sets
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOrganizing Test Source Sets — src/test/
, src/androidTest/
, and the KMP Split
src/test/src/androidTest/组织测试源集(Source Set)——src/test/
、src/androidTest/
与 KMP 拆分
src/test/src/androidTest/Where a test file lives determines which JVM runs it, which dependencies it sees, and whether it ships in the test APK. Most modules need only and . Modules that share helpers between host and device tests historically used (a Codelab convention, not Google-documented as such), which broke on AGP 7.2+ and pushed Compose itself to the KMP-style / split. This skill encodes the matrix so the agent can place a test file with confidence.
src/test/src/androidTest/src/sharedTest/androidHostTestandroidDeviceTest测试文件所在的位置决定了由哪个 JVM 运行它、可以看到哪些依赖,以及它是否会随测试 APK 一起打包。大多数模块只需要 和 。历史上,需要在主机测试与设备测试之间共享辅助代码的模块会使用 (这是 Codelab 中的约定,并非 Google 明确记录的约定),但该方式在 AGP 7.2+ 上失效,并促使 Compose 本身转向 KMP 风格的 / 拆分。此 skill 固化了这一矩阵,使 Agent 能够有把握地放置测试文件。
src/test/src/androidTest/src/sharedTest/androidHostTestandroidDeviceTestWhen to use this skill
何时使用此 skill
- The user asks "where do I put my tests" or "src/test/ or src/androidTest/".
- The user asks "what's testImplementation vs androidTestImplementation vs debugImplementation".
- The user reports and the agent suspects the dependency is on the wrong configuration.
Unresolved reference: createComposeRule - The user is migrating off after AGP 7.2+ broke their
src/sharedTest/block.sourceSets { test.java.srcDir(...) } - The user mentions /
androidHostTestand asks how to set them up in a non-KMP module.androidDeviceTest - The user asks "why is my Robolectric test in " — it should be in
src/androidTest/.src/test/
- 用户询问“测试应该放在哪里”或“还是
src/test/”。src/androidTest/ - 用户询问“与
testImplementation、androidTestImplementation有什么区别”。debugImplementation - 用户报告 ,且 Agent 怀疑依赖配置不正确。
Unresolved reference: createComposeRule - 用户在 AGP 7.2+ 破坏 配置块后,准备从
sourceSets { test.java.srcDir(...) }迁移。src/sharedTest/ - 用户提到 /
androidHostTest,并询问如何在非 KMP 模块中配置。androidDeviceTest - 用户询问“为什么我的 Robolectric 测试位于 ”——它应该位于
src/androidTest/。src/test/
When NOT to use this skill
何时不应使用此 skill
- The user is wiring Gradle dependencies for Compose test (,
ui-test-junit4) — useui-test-manifest.../../../compose/setup/configuring-test-dependencies/SKILL.md - The user is choosing test scope (small/medium/big) — use .
../../concepts/understanding-the-testing-pyramid/SKILL.md - The user is configuring itself — use
AndroidJUnitRunner.../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - The user is configuring a JUnit4 runner for JVM tests — use .
../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md
- 用户正在为 Compose 测试配置 Gradle 依赖(、
ui-test-junit4)——请使用ui-test-manifest。../../../compose/setup/configuring-test-dependencies/SKILL.md - 用户正在选择测试范围(小型/中型/大型)——请使用 。
../../concepts/understanding-the-testing-pyramid/SKILL.md - 用户正在配置 本身——请使用
AndroidJUnitRunner。../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - 用户正在为 JVM 测试配置 JUnit4 runner——请使用 。
../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md
Prerequisites
前置条件
- A module with the Android Gradle Plugin (or
com.android.application).com.android.library - Familiarity with Gradle configuration names (,
testImplementation,androidTestImplementation).debugImplementation - An understanding that JVM tests run on the host's JVM and instrumented tests run on a device/emulator. (See .)
../../concepts/understanding-the-testing-pyramid/SKILL.md
- 一个使用 Android Gradle Plugin(或
com.android.application)的模块。com.android.library - 熟悉 Gradle 配置名称(、
testImplementation、androidTestImplementation)。debugImplementation - 理解 JVM 测试在主机的 JVM 上运行,而插桩测试在设备或模拟器上运行。(参见 。)
../../concepts/understanding-the-testing-pyramid/SKILL.md
The two source sets Google documents
Google 有文档说明的两个源集
src/test/
— local JVM tests
src/test/src/test/
——本地 JVM 测试
src/test/Per :
/training/testing/local-tests"By default, the source files for local unit tests are placed in. This directory already exists when you create a new project using Android Studio." —module-name/src/test/developer.android.com/training/testing/local-tests
"A local test runs directly on your own workstation, rather than an Android device or emulator. As such, it uses your local Java Virtual Machine (JVM)." —developer.android.com/training/testing/local-tests
Driven by . Runs via or . No Android device, no emulator. The Android framework is unavailable unless Robolectric simulates it.
testImplementation./gradlew test./gradlew testDebugUnitTest根据 :
/training/testing/local-tests“默认情况下,本地单元测试的源文件放在中。使用 Android Studio 创建新项目时,该目录已经存在。” —module-name/src/test/developer.android.com/training/testing/local-tests
“本地测试直接在你的工作站上运行,而不是在 Android 设备或模拟器上运行。因此,它使用本机的 Java Virtual Machine(JVM)。” —developer.android.com/training/testing/local-tests
由 驱动。通过 或 运行。无需 Android 设备或模拟器。除非使用 Robolectric 模拟,否则无法使用 Android framework。
testImplementation./gradlew test./gradlew testDebugUnitTestsrc/androidTest/
— instrumented tests
src/androidTest/src/androidTest/
——插桩测试
src/androidTest/Per :
/training/testing/instrumented-tests"In your Android Studio project, you store the source files for instrumented tests in. This directory already exists when you create a new project and contains an example instrumented test." —module-name/src/androidTest/java/developer.android.com/training/testing/instrumented-tests
Driven by . Runs via or . Requires a connected device or emulator. Uses per CORPUS §H.2.
androidTestImplementation./gradlew connectedAndroidTest./gradlew connectedDebugAndroidTestAndroidJUnitRunnerThe page is also explicit on the vs split:
testImplementationandroidTestImplementation"Note:adds dependencies for local tests andtestImplementationadds dependencies for Instrumented tests." —androidTestImplementationdeveloper.android.com/training/testing/local-tests
根据 :
/training/testing/instrumented-tests“在 Android Studio 项目中,你将插桩测试的源文件存放在中。该目录已经存在,并包含一个插桩测试示例。” —module-name/src/androidTest/java/developer.android.com/training/testing/instrumented-tests
由 驱动。通过 或 运行。需要连接设备或模拟器。根据 CORPUS §H.2,使用 。
androidTestImplementation./gradlew connectedAndroidTest./gradlew connectedDebugAndroidTestAndroidJUnitRunner该页面也明确说明了 与 的区别:
testImplementationandroidTestImplementation“注意:为本地测试添加依赖,testImplementation为插桩测试添加依赖。” —androidTestImplementationdeveloper.android.com/training/testing/local-tests
The configuration matrix
配置矩阵
Configuration Source set Variant Ships in
-----------------------------------------------------------------------------------
implementation main all release + debug + tests
api main all release + debug + tests
debugImplementation debug only debug debug APK + androidTest APK
releaseImplementation release only release release APK only
testImplementation src/test/ all (host) JVM test classpath
testDebugImplementation src/test/ debug (host) JVM test classpath, debug only
androidTestImplementation src/androidTest/ all (device) androidTest APK
androidTestUtil n/a all orchestrator/util install (NOT classpath)Three configurations the agent must keep straight:
- — JVM (host) tests. Includes Mockito, MockK, Robolectric, kotlinx-coroutines-test, Turbine.
testImplementation - — instrumented (device) tests. Includes Espresso, UiAutomator, AndroidJUnitRunner, Compose
androidTestImplementation.ui-test-junit4 - — main
debugImplementationvariant. Used bydebugandandroidx.compose.ui:ui-test-manifestbecause the test APK is built on top of the debug APK and needs the manifest entries merged in.androidx.fragment:fragment-testing-manifest
androidx.compose.ui:ui-test-manifestdebugImplementationandroidTestImplementation../../../compose/setup/configuring-test-dependencies/SKILL.mdTestManifestGradleConfigurationConfiguration Source set Variant Ships in
-----------------------------------------------------------------------------------
implementation main all release + debug + tests
api main all release + debug + tests
debugImplementation debug only debug debug APK + androidTest APK
releaseImplementation release only release release APK only
testImplementation src/test/ all (host) JVM test classpath
testDebugImplementation src/test/ debug (host) JVM test classpath, debug only
androidTestImplementation src/androidTest/ all (device) androidTest APK
androidTestUtil n/a all orchestrator/util install (NOT classpath)Agent 必须区分清楚以下三种配置:
- ——JVM(主机)测试。适用于 Mockito、MockK、Robolectric、kotlinx-coroutines-test、Turbine。
testImplementation - ——插桩(设备)测试。适用于 Espresso、UiAutomator、AndroidJUnitRunner、Compose
androidTestImplementation。ui-test-junit4 - ——主
debugImplementationvariant。debug和androidx.compose.ui:ui-test-manifest需要使用此配置,因为测试 APK 构建于 debug APK 之上,并且需要合并相应的 manifest 条目。androidx.fragment:fragment-testing-manifest
androidx.compose.ui:ui-test-manifestdebugImplementationandroidTestImplementationTestManifestGradleConfiguration../../../compose/setup/configuring-test-dependencies/SKILL.mdsrc/sharedTest/
— community convention, NOT Google-documented
src/sharedTest/src/sharedTest/
——社区约定,并非 Google 文档说明的约定
src/sharedTest/Per :
tasks/research/R8-android-fundamentals.mdis not mentioned by name on any of the six in-scopesrc/sharedTest/pages or on the fetched Hilt-testing / rules pages.developer.android.com/training/testing/...
It originated in Google's own Architecture Blueprints sample and the Advanced Android Testing Codelab. The pattern uses Gradle to inject the same Java/Kotlin folder into BOTH and :
sourceSetstestandroidTestkotlin
// pre-AGP 7.2 — the classic sharedTest wiring
android {
sourceSets {
getByName("test").java.srcDir("src/sharedTest/java")
getByName("androidTest").java.srcDir("src/sharedTest/java")
}
}Why it existed: write a test once, run it as a fast Robolectric host test in CI and as a high-fidelity instrumented test on emulator. The test class uses (which dispatches correctly in both environments per CORPUS §G.6).
androidx.test.ext.junit.runners.AndroidJUnit4Why it broke: AGP 7.2+ enforces that the same source directory cannot be shared across multiple source sets at build time — the build itself refuses, with an error pointing at the duplicated call. (The mode of failure is build-time refusal in AGP, not a runtime .) Tracked at https://github.com/robolectric/robolectric/issues/7432 (Robolectric maintainer thread, with reproductions and AGP-version table). Many modules either:
srcDir(...)LinkageError- Stopped sharing tests and accepted duplication.
- Migrated to a separate Gradle sub-module () that ships test helpers via
:core-testingandtestImplementation.androidTestImplementation - Adopted KMP-style source set names (/
androidHostTest).androidDeviceTest
根据 :
tasks/research/R8-android-fundamentals.md在六个纳入范围的页面以及获取到的 Hilt 测试/rules 页面中,均未明确提及developer.android.com/training/testing/...。src/sharedTest/
该约定源自 Google 自己的 Architecture Blueprints 示例和 Advanced Android Testing Codelab。它使用 Gradle ,将同一个 Java/Kotlin 目录同时注入 和 :
sourceSetstestandroidTestkotlin
// pre-AGP 7.2 — the classic sharedTest wiring
android {
sourceSets {
getByName("test").java.srcDir("src/sharedTest/java")
getByName("androidTest").java.srcDir("src/sharedTest/java")
}
}采用它的原因:只需编写一次测试,即可在 CI 中将其作为速度较快的 Robolectric 主机测试运行,也可在模拟器上将其作为高保真插桩测试运行。测试类使用 ,根据 CORPUS §G.6,该 runner 能在两种环境中正确分派测试。
androidx.test.ext.junit.runners.AndroidJUnit4它失效的原因:AGP 7.2+ 在构建时规定同一个源目录不能由多个源集共享——构建本身会直接拒绝,并报告与重复的 调用相关的错误。(失败形式是 AGP 在构建时拒绝执行,而不是运行时出现 。)相关问题记录于 https://github.com/robolectric/robolectric/issues/7432(Robolectric 维护者讨论线程,其中包含复现案例和 AGP 版本对照表)。许多模块采取了以下方式:
srcDir(...)LinkageError- 停止共享测试并接受代码重复。
- 迁移到独立的 Gradle 子模块(),通过
:core-testing和testImplementation提供测试辅助代码。androidTestImplementation - 采用 KMP 风格的源集名称(/
androidHostTest)。androidDeviceTest
KMP-style androidHostTest
/ androidDeviceTest
androidHostTestandroidDeviceTestKMP 风格的 androidHostTest
/ androidDeviceTest
androidHostTestandroidDeviceTestCompose UI tests internally use this layout, per CORPUS §C ("Source set conventions (KMP)"):
commonTest
└── androidCommonTest (helpers shared by host + device)
├── androidDeviceTest (instrumentation APK on emulator/device)
└── androidHostTest (Robolectric on JVM)Real androidx evidence: is a host (Robolectric) test, while is a device test. Both compile against for shared helpers.
compose/ui/ui-test/src/androidHostTest/kotlin/androidx/compose/ui/test/RobolectricComposeTest.ktcompose/material3/material3/src/androidDeviceTest/.../SwitchTest.ktcommonTestFor non-KMP Android-only modules, the same effect can be approximated with separate sub-modules:
kotlin
// :feature:home/build.gradle.kts — production module
plugins { id("com.android.library") }
dependencies {
testImplementation(project(":feature:home-testing"))
androidTestImplementation(project(":feature:home-testing"))
}
// :feature:home-testing/build.gradle.kts — pure Kotlin or Android-library "test fixtures"
plugins { id("java-library") } // or com.android.library if Android types neededThe module hosts , , custom matchers — anything both host and device tests want.
:feature:home-testingFakeUserRepositoryMainDispatcherRuleAlternative: AGP 7.0+ flag (), which exposes Gradle artifacts for and is consumable from sibling modules' / .
testFixturesandroid { testFixtures { enable = true } }testFixtures()testFixturesImplementationtestImplementationandroidTestImplementationMUST NOT cite for — none of those pages document it. MUST cite the Architecture Blueprints repo or instead.
developer.android.com/training/testing/...sharedTesttasks/research/R8-android-fundamentals.md根据 CORPUS §C(“Source set conventions (KMP)”),Compose UI 测试内部使用以下结构:
commonTest
└── androidCommonTest (helpers shared by host + device)
├── androidDeviceTest (instrumentation APK on emulator/device)
└── androidHostTest (Robolectric on JVM)androidx 中的实际证据: 是主机(Robolectric)测试,而 是设备测试。两者都会针对 中的共享辅助代码进行编译。
compose/ui/ui-test/src/androidHostTest/kotlin/androidx/compose/ui/test/RobolectricComposeTest.ktcompose/material3/material3/src/androidDeviceTest/.../SwitchTest.ktcommonTest对于仅支持 Android 的非 KMP 模块,可以使用独立子模块来实现类似效果:
kotlin
// :feature:home/build.gradle.kts — production module
plugins { id("com.android.library") }
dependencies {
testImplementation(project(":feature:home-testing"))
androidTestImplementation(project(":feature:home-testing"))
}
// :feature:home-testing/build.gradle.kts — pure Kotlin or Android-library "test fixtures"
plugins { id("java-library") } // or com.android.library if Android types needed:feature:home-testingFakeUserRepositoryMainDispatcherRule另一种方案是使用 AGP 7.0+ 的 开关()。它会公开 Gradle artifact 和 ,可供同级模块通过 / 使用。
testFixturesandroid { testFixtures { enable = true } }testFixtures()testFixturesImplementationtestImplementationandroidTestImplementation不得将 作为 的引用来源——这些页面均未记录该约定。应改为引用 Architecture Blueprints 仓库或 。
developer.android.com/training/testing/...sharedTesttasks/research/R8-android-fundamentals.mdFile placement decision tree
测试文件位置决策树
Where does this test go?
│
├── Pure Kotlin/JVM logic, no Android framework → src/test/
│ (testImplementation deps)
│
├── Robolectric (Android framework simulated on JVM) → src/test/
│ (testImplementation deps + Robolectric)
│ NOT src/androidTest/.
│
├── ViewModel + coroutines + fakes → src/test/
│
├── Real Room database integration → src/androidTest/
│ (small instrumented test per /fundamentals)
│
├── Espresso UI test → src/androidTest/
├── UiAutomator cross-app test → src/androidTest/
├── Compose UI test against real Activity → src/androidTest/
│ + debugImplementation("...:ui-test-manifest")
│
├── Compose UI test on Robolectric → src/test/
│ (testImplementation("...:ui-test-junit4") + Robolectric)
│
├── Test helper (FakeRepository, MainDispatcherRule) → :core-testing module OR src/sharedTest/
│ (with the AGP 7.2+ caveats above)Where does this test go?
│
├── Pure Kotlin/JVM logic, no Android framework → src/test/
│ (testImplementation deps)
│
├── Robolectric (Android framework simulated on JVM) → src/test/
│ (testImplementation deps + Robolectric)
│ NOT src/androidTest/.
│
├── ViewModel + coroutines + fakes → src/test/
│
├── Real Room database integration → src/androidTest/
│ (small instrumented test per /fundamentals)
│
├── Espresso UI test → src/androidTest/
├── UiAutomator cross-app test → src/androidTest/
├── Compose UI test against real Activity → src/androidTest/
│ + debugImplementation("...:ui-test-manifest")
│
├── Compose UI test on Robolectric → src/test/
│ (testImplementation("...:ui-test-junit4") + Robolectric)
│
├── Test helper (FakeRepository, MainDispatcherRule) → :core-testing module OR src/sharedTest/
│ (with the AGP 7.2+ caveats above)Patterns
模式
Pattern: WRONG vs RIGHT — testImplementation
vs androidTestImplementation
testImplementationandroidTestImplementation模式:错误与正确——testImplementation
与 androidTestImplementation
testImplementationandroidTestImplementationkotlin
// WRONG — Espresso on testImplementation
dependencies {
testImplementation("androidx.test.espresso:espresso-core:3.7.0")
testImplementation("androidx.test.ext:junit:1.3.0")
}
// WRONG because: Espresso requires a real or simulated Android device. testImplementation
// only puts the JAR on the JVM classpath. The test compiles but ClassNotFoundException /
// IllegalStateException at runtime when Espresso looks for an Instrumentation instance.kotlin
// RIGHT — Espresso on androidTestImplementation
dependencies {
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
androidTestImplementation("androidx.test.ext:junit:1.3.0")
}kotlin
// WRONG — Espresso on testImplementation
dependencies {
testImplementation("androidx.test.espresso:espresso-core:3.7.0")
testImplementation("androidx.test.ext:junit:1.3.0")
}
// WRONG because: Espresso requires a real or simulated Android device. testImplementation
// only puts the JAR on the JVM classpath. The test compiles but ClassNotFoundException /
// IllegalStateException at runtime when Espresso looks for an Instrumentation instance.kotlin
// RIGHT — Espresso on androidTestImplementation
dependencies {
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
androidTestImplementation("androidx.test.ext:junit:1.3.0")
}Pattern: WRONG vs RIGHT — Robolectric in src/androidTest/
src/androidTest/模式:错误与正确——在 src/androidTest/
中使用 Robolectric
src/androidTest/kotlin
// WRONG
// src/androidTest/java/com/example/SomeRobolectricTest.kt
@RunWith(RobolectricTestRunner::class)
class SomeRobolectricTest { /* ... */ }
// WRONG because: Robolectric is a JVM Android simulator (per /fundamentals: "Big local test:
// You can use an Android simulator that runs locally, such as Robolectric"). It belongs in
// src/test/. Putting it in src/androidTest/ either fails to find Robolectric (which is on
// testImplementation) or runs it on the device JVM where its shadow mechanism does not work.kotlin
// RIGHT
// src/test/java/com/example/SomeRobolectricTest.kt
@RunWith(AndroidJUnit4::class) // dispatches to Robolectric on JVM
@Config(sdk = [Build.VERSION_CODES.UPSIDE_DOWN_CAKE])
class SomeRobolectricTest { /* ... */ }kotlin
// WRONG
// src/androidTest/java/com/example/SomeRobolectricTest.kt
@RunWith(RobolectricTestRunner::class)
class SomeRobolectricTest { /* ... */ }
// WRONG because: Robolectric is a JVM Android simulator (per /fundamentals: "Big local test:
// You can use an Android simulator that runs locally, such as Robolectric"). It belongs in
// src/test/. Putting it in src/androidTest/ either fails to find Robolectric (which is on
// testImplementation) or runs it on the device JVM where its shadow mechanism does not work.kotlin
// RIGHT
// src/test/java/com/example/SomeRobolectricTest.kt
@RunWith(AndroidJUnit4::class) // dispatches to Robolectric on JVM
@Config(sdk = [Build.VERSION_CODES.UPSIDE_DOWN_CAKE])
class SomeRobolectricTest { /* ... */ }Pattern: WRONG vs RIGHT — ui-test-manifest
configuration
ui-test-manifest模式:错误与正确——ui-test-manifest
配置
ui-test-manifestkotlin
// WRONG
dependencies {
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
androidTestImplementation("androidx.compose.ui:ui-test-manifest") // wrong config
}
// WRONG because: ui-test-manifest contributes <activity android:name="ComponentActivity">
// to the merged debug APK manifest. On androidTestImplementation, the merger does not pick
// it up; createComposeRule() crashes with ActivityNotFoundException. Lint also flags this
// as TestManifestGradleConfiguration (WARNING).kotlin
// RIGHT
dependencies {
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}See for the lint detail.
../../../compose/setup/configuring-test-dependencies/SKILL.mdkotlin
// WRONG
dependencies {
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
androidTestImplementation("androidx.compose.ui:ui-test-manifest") // wrong config
}
// WRONG because: ui-test-manifest contributes <activity android:name="ComponentActivity">
// to the merged debug APK manifest. On androidTestImplementation, the merger does not pick
// it up; createComposeRule() crashes with ActivityNotFoundException. Lint also flags this
// as TestManifestGradleConfiguration (WARNING).kotlin
// RIGHT
dependencies {
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}有关 lint 详情,请参阅 。
../../../compose/setup/configuring-test-dependencies/SKILL.mdPattern: AGP 7.2+ sharedTest
migration
sharedTest模式:迁移 AGP 7.2+ 中的 sharedTest
sharedTestkotlin
// BROKE on AGP 7.2+
android {
sourceSets {
getByName("test").java.srcDir("src/sharedTest/java")
getByName("androidTest").java.srcDir("src/sharedTest/java")
}
}kotlin
// MIGRATION OPTION A — extract a :core-testing sub-module
// :core-testing/build.gradle.kts
plugins { id("java-library") }
// classes here are consumed by both test sourcesets in dependent modules
// :feature:home/build.gradle.kts
dependencies {
testImplementation(project(":core-testing"))
androidTestImplementation(project(":core-testing"))
}kotlin
// MIGRATION OPTION B — testFixtures
android {
testFixtures { enable = true }
}
// src/testFixtures/java/... contains FakeUserRepository, MainDispatcherRule
// dependent module
dependencies {
testImplementation(testFixtures(project(":core")))
androidTestImplementation(testFixtures(project(":core")))
}kotlin
// MIGRATION OPTION C — KMP source-set naming
// In a KMP Android module:
kotlin {
androidTarget {
compilations.getByName("debug") { /* ... */ }
}
sourceSets {
val androidHostTest by getting // Robolectric, JVM
val androidDeviceTest by getting // emulator/device
val androidCommonTest by getting // helpers shared by both
androidHostTest.dependsOn(androidCommonTest)
androidDeviceTest.dependsOn(androidCommonTest)
}
}Compose itself uses Option C internally (per CORPUS §B "Source set conventions").
kotlin
// BROKE on AGP 7.2+
android {
sourceSets {
getByName("test").java.srcDir("src/sharedTest/java")
getByName("androidTest").java.srcDir("src/sharedTest/java")
}
}kotlin
// MIGRATION OPTION A — extract a :core-testing sub-module
// :core-testing/build.gradle.kts
plugins { id("java-library") }
// classes here are consumed by both test sourcesets in dependent modules
// :feature:home/build.gradle.kts
dependencies {
testImplementation(project(":core-testing"))
androidTestImplementation(project(":core-testing"))
}kotlin
// MIGRATION OPTION B — testFixtures
android {
testFixtures { enable = true }
}
// src/testFixtures/java/... contains FakeUserRepository, MainDispatcherRule
// dependent module
dependencies {
testImplementation(testFixtures(project(":core")))
androidTestImplementation(testFixtures(project(":core")))
}kotlin
// MIGRATION OPTION C — KMP source-set naming
// In a KMP Android module:
kotlin {
androidTarget {
compilations.getByName("debug") { /* ... */ }
}
sourceSets {
val androidHostTest by getting // Robolectric, JVM
val androidDeviceTest by getting // emulator/device
val androidCommonTest by getting // helpers shared by both
androidHostTest.dependsOn(androidCommonTest)
androidDeviceTest.dependsOn(androidCommonTest)
}
}根据 CORPUS §B“Source set conventions”,Compose 内部使用选项 C。
Module-level Gradle sample
模块级 Gradle 示例
kotlin
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.example.feature.home"
compileSdk = 35
defaultConfig {
minSdk = 23
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
testOptions {
unitTests.isIncludeAndroidResources = true // required for Robolectric
animationsDisabled = true // hermetic instrumented tests
}
}
dependencies {
// production
implementation("androidx.activity:activity-compose")
// host (JVM) tests — src/test/
testImplementation("junit:junit:4.13.2")
testImplementation("androidx.test:core:1.7.0")
testImplementation("androidx.test.ext:junit:1.3.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.0")
testImplementation("org.mockito:mockito-core:5.13.0")
testImplementation("org.mockito.kotlin:mockito-kotlin:5.4.0")
testImplementation("org.robolectric:robolectric:4.13")
testImplementation("app.cash.turbine:turbine:1.1.0")
// instrumented (device) tests — src/androidTest/
androidTestImplementation("androidx.test.ext:junit:1.3.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
// debug-only — merged manifest entries for test scaffolds
debugImplementation("androidx.compose.ui:ui-test-manifest")
debugImplementation("androidx.fragment:fragment-testing-manifest:1.8.5")
// orchestrator (note: androidTestUtil, not androidTestImplementation)
androidTestUtil("androidx.test:orchestrator:1.6.1")
}kotlin
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.example.feature.home"
compileSdk = 35
defaultConfig {
minSdk = 23
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
testOptions {
unitTests.isIncludeAndroidResources = true // required for Robolectric
animationsDisabled = true // hermetic instrumented tests
}
}
dependencies {
// production
implementation("androidx.activity:activity-compose")
// host (JVM) tests — src/test/
testImplementation("junit:junit:4.13.2")
testImplementation("androidx.test:core:1.7.0")
testImplementation("androidx.test.ext:junit:1.3.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.0")
testImplementation("org.mockito:mockito-core:5.13.0")
testImplementation("org.mockito.kotlin:mockito-kotlin:5.4.0")
testImplementation("org.robolectric:robolectric:4.13")
testImplementation("app.cash.turbine:turbine:1.1.0")
// instrumented (device) tests — src/androidTest/
androidTestImplementation("androidx.test.ext:junit:1.3.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
// debug-only — merged manifest entries for test scaffolds
debugImplementation("androidx.compose.ui:ui-test-manifest")
debugImplementation("androidx.fragment:fragment-testing-manifest:1.8.5")
// orchestrator (note: androidTestUtil, not androidTestImplementation)
androidTestUtil("androidx.test:orchestrator:1.6.1")
}Mandatory rules
强制规则
- MUST put pure Kotlin / JVM tests in with
src/test/deps.testImplementation - MUST put Robolectric tests in . Robolectric is a JVM Android simulator, not an instrumented runner.
src/test/ - MUST put real-device / emulator tests in with
src/androidTest/deps.androidTestImplementation - MUST put and
androidx.compose.ui:ui-test-manifestonandroidx.fragment:fragment-testing-manifest, neverdebugImplementation.androidTestImplementation - MUST NOT cite as the source for
developer.android.com/training/testing/.... It is not documented there. Cite the Architecture Blueprints repo orsrc/sharedTest/.tasks/research/R8-android-fundamentals.md - MUST NOT add Espresso, UiAutomator, or to
ui-test-junit4. They will compile but fail at runtime when notestImplementationis present.Instrumentation - PREFERRED: for shared test helpers, extract a Gradle sub-module or use
:core-testingrather than the AGP-7.2-fragileandroid.testFixtures.enable = truesource set.sharedTest - PREFERRED: in KMP modules, follow Compose's lead — for helpers,
androidCommonTestfor Robolectric,androidHostTestfor emulator tests.androidDeviceTest - PREFERRED: name backtick test methods freely in ; restrict to API 30+ devices in
src/test/persrc/androidTest/./training/testing/instrumented-tests
- 必须将纯 Kotlin / JVM 测试放在 ,并使用
src/test/依赖。testImplementation - 必须将 Robolectric 测试放在 。Robolectric 是 JVM Android 模拟器,而不是插桩 runner。
src/test/ - 必须将真实设备或模拟器测试放在 ,并使用
src/androidTest/依赖。androidTestImplementation - 必须将 和
androidx.compose.ui:ui-test-manifest放在androidx.fragment:fragment-testing-manifest,绝不能放在debugImplementation。androidTestImplementation - 不得将 作为
developer.android.com/training/testing/...的来源。这些页面并未记录该约定。应引用 Architecture Blueprints 仓库或src/sharedTest/。tasks/research/R8-android-fundamentals.md - 不得将 Espresso、UiAutomator 或 添加到
ui-test-junit4。当环境中不存在testImplementation时,它们虽然可以编译,但运行时必然失败。Instrumentation - **首选:**对于共享测试辅助代码,提取 Gradle 子模块或启用
:core-testing,而不是使用容易被 AGP 7.2 破坏的android.testFixtures.enable = true源集。sharedTest - **首选:**在 KMP 模块中遵循 Compose 的做法——使用 存放辅助代码,使用
androidCommonTest运行 Robolectric 测试,使用androidHostTest运行模拟器测试。androidDeviceTest - **首选:**在 中可以自由使用反引号包裹的测试方法名称;根据
src/test/,在/training/testing/instrumented-tests中应仅将其用于 API 30+ 设备。src/androidTest/
Verification
验证
- No Robolectric test exists under . Run
src/androidTest/; expect empty output.find src/androidTest -name '*.kt' -exec grep -l 'org.robolectric' {} + - No Espresso / UiAutomator import exists under . Run
src/test/; expect empty output.find src/test -name '*.kt' -exec grep -l 'androidx.test.espresso\|androidx.test.uiautomator' {} + - is declared exactly on
androidx.compose.ui:ui-test-manifest. RundebugImplementation; expect no./gradlew :<module>:lintwarning.TestManifestGradleConfiguration - runs JVM tests without invoking
./gradlew :<module>:testDebugUnitTest.connectedDebugAndroidTest - invokes only tests under
./gradlew :<module>:connectedDebugAndroidTest(verify withsrc/androidTest/output).--info - If shared helpers exist, they live in a sub-module, in
:core-testing, or intestFixtures— never in a literalandroidCommonTestfolder wired viasrc/sharedTest/.sourceSets { ... srcDir(...) } - is set when any host test references
testOptions.unitTests.isIncludeAndroidResources = true.R.*
- 下不存在 Robolectric 测试。运行
src/androidTest/;预期无输出。find src/androidTest -name '*.kt' -exec grep -l 'org.robolectric' {} + - 下不存在 Espresso / UiAutomator import。运行
src/test/;预期无输出。find src/test -name '*.kt' -exec grep -l 'androidx.test.espresso\|androidx.test.uiautomator' {} + - 仅在
androidx.compose.ui:ui-test-manifest中声明。运行debugImplementation;预期不会出现./gradlew :<module>:lint警告。TestManifestGradleConfiguration - 可运行 JVM 测试,而不会调用
./gradlew :<module>:testDebugUnitTest。connectedDebugAndroidTest - 只运行
./gradlew :<module>:connectedDebugAndroidTest下的测试(通过src/androidTest/输出验证)。--info - 如果存在共享测试辅助代码,其位置应为 子模块、
:core-testing或testFixtures,绝不能位于通过androidCommonTest接入的字面意义上的sourceSets { ... srcDir(...) }目录中。src/sharedTest/ - 当任何主机测试引用 时,应设置
R.*。testOptions.unitTests.isIncludeAndroidResources = true
References
参考资料
- —
developer.android.com/training/testing/local-tests,src/test/, "local test runs directly on your own workstation".testImplementation - —
developer.android.com/training/testing/instrumented-tests,src/androidTest/, AndroidJUnitRunner, backtick caveat.androidTestImplementation - — "Big local test: You can use an Android simulator that runs locally, such as Robolectric".
developer.android.com/training/testing/fundamentals - — verbatim quotes; documents that
tasks/research/R8-android-fundamentals.mdis NOT on any of the six in-scopesrc/sharedTest/pages./training/testing/... - Architecture Blueprints (origin of the pattern): https://github.com/android/architecture-samples
sharedTest - AGP source-set documentation: https://developer.android.com/build/build-variants#sourcesets
- flag: https://developer.android.com/build/dependencies#test-fixtures
testFixtures - CORPUS §C "Source set conventions (KMP)" — Compose's internal /
androidHostTestlayout.androidDeviceTest - — canonical host-test skeleton in androidx.
compose/ui/ui-test/src/androidHostTest/kotlin/androidx/compose/ui/test/RobolectricComposeTest.kt - — canonical device-test skeleton.
compose/material3/material3/src/androidDeviceTest/.../SwitchTest.kt - Sibling skills: ,
../../concepts/understanding-the-testing-pyramid/SKILL.md,../../concepts/choosing-what-to-test/SKILL.md,../../doubles/picking-test-doubles/SKILL.md.../applying-testing-strategies/SKILL.md - Cross-category: ,
../../../compose/setup/configuring-test-dependencies/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.../../../adb/tests/running-instrumented-tests-via-adb/SKILL.md
- ——
developer.android.com/training/testing/local-tests、src/test/、“本地测试直接在自己的工作站上运行”。testImplementation - ——
developer.android.com/training/testing/instrumented-tests、src/androidTest/、AndroidJUnitRunner、反引号注意事项。androidTestImplementation - ——“大型本地测试:可以使用在本地运行的 Android 模拟器,例如 Robolectric”。
developer.android.com/training/testing/fundamentals - ——原文引述;说明
tasks/research/R8-android-fundamentals.md并未出现在六个纳入范围的src/sharedTest/页面中。/training/testing/... - Architecture Blueprints(约定的起源):https://github.com/android/architecture-samples
sharedTest - AGP source set 文档:https://developer.android.com/build/build-variants#sourcesets
- 开关:https://developer.android.com/build/dependencies#test-fixtures
testFixtures - CORPUS §C“Source set conventions (KMP)”——Compose 内部的 /
androidHostTest结构。androidDeviceTest - ——androidx 中典型的 host test 骨架。
compose/ui/ui-test/src/androidHostTest/kotlin/androidx/compose/ui/test/RobolectricComposeTest.kt - ——典型的 device test 骨架。
compose/material3/material3/src/androidDeviceTest/.../SwitchTest.kt - 同级 skill:、
../../concepts/understanding-the-testing-pyramid/SKILL.md、../../concepts/choosing-what-to-test/SKILL.md、../../doubles/picking-test-doubles/SKILL.md。../applying-testing-strategies/SKILL.md - 跨分类 skill:、
../../../compose/setup/configuring-test-dependencies/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。../../../adb/tests/running-instrumented-tests-via-adb/SKILL.md