organizing-test-source-sets

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Organizing Test Source Sets —
src/test/
,
src/androidTest/
, and the KMP Split

组织测试源集(Source Set)——
src/test/
、
src/androidTest/
与 KMP 拆分

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
src/test/
and
src/androidTest/
. Modules that share helpers between host and device tests historically used
src/sharedTest/
(a Codelab convention, not Google-documented as such), which broke on AGP 7.2+ and pushed Compose itself to the KMP-style
androidHostTest
/
androidDeviceTest
split. This skill encodes the matrix so the agent can place a test file with confidence.
测试文件所在的位置决定了由哪个 JVM 运行它、可以看到哪些依赖,以及它是否会随测试 APK 一起打包。大多数模块只需要
src/test/
和
src/androidTest/
。历史上,需要在主机测试与设备测试之间共享辅助代码的模块会使用
src/sharedTest/
(这是 Codelab 中的约定,并非 Google 明确记录的约定),但该方式在 AGP 7.2+ 上失效,并促使 Compose 本身转向 KMP 风格的
androidHostTest
/
androidDeviceTest
拆分。此 skill 固化了这一矩阵,使 Agent 能够有把握地放置测试文件。

When 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
    Unresolved reference: createComposeRule
    and the agent suspects the dependency is on the wrong configuration.
  • The user is migrating off
    src/sharedTest/
    after AGP 7.2+ broke their
    sourceSets { test.java.srcDir(...) }
    block.
  • The user mentions
    androidHostTest
    /
    androidDeviceTest
    and asks how to set them up in a non-KMP module.
  • The user asks "why is my Robolectric test in
    src/androidTest/
    " — it should be in
    src/test/
    .
  • 用户询问“测试应该放在哪里”或“
    src/test/
    还是
    src/androidTest/
    ”。
  • 用户询问“
    testImplementation
    与
    androidTestImplementation
    、
    debugImplementation
    有什么区别”。
  • 用户报告
    Unresolved reference: createComposeRule
    ,且 Agent 怀疑依赖配置不正确。
  • 用户在 AGP 7.2+ 破坏
    sourceSets { test.java.srcDir(...) }
    配置块后,准备从
    src/sharedTest/
    迁移。
  • 用户提到
    androidHostTest
    /
    androidDeviceTest
    ,并询问如何在非 KMP 模块中配置。
  • 用户询问“为什么我的 Robolectric 测试位于
    src/androidTest/
    ”——它应该位于
    src/test/
    。

When NOT to use this skill

何时不应使用此 skill

  • The user is wiring Gradle dependencies for Compose test (
    ui-test-junit4
    ,
    ui-test-manifest
    ) — use
    ../../../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
    AndroidJUnitRunner
    itself — use
    ../../../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 (
    com.android.application
    or
    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/
——本地 JVM 测试

Per
/training/testing/local-tests
:
"By default, the source files for local unit tests are placed in
module-name/src/test/
. This directory already exists when you create a new project using Android Studio." —
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
testImplementation
. Runs via
./gradlew test
or
./gradlew testDebugUnitTest
. No Android device, no emulator. The Android framework is unavailable unless Robolectric simulates it.
根据
/training/testing/local-tests
:
“默认情况下,本地单元测试的源文件放在
module-name/src/test/
中。使用 Android Studio 创建新项目时,该目录已经存在。” —
developer.android.com/training/testing/local-tests
“本地测试直接在你的工作站上运行,而不是在 Android 设备或模拟器上运行。因此,它使用本机的 Java Virtual Machine(JVM)。” —
developer.android.com/training/testing/local-tests
由
testImplementation
驱动。通过
./gradlew test
或
./gradlew testDebugUnitTest
运行。无需 Android 设备或模拟器。除非使用 Robolectric 模拟,否则无法使用 Android framework。

src/androidTest/
— instrumented tests

src/androidTest/
——插桩测试

Per
/training/testing/instrumented-tests
:
"In your Android Studio project, you store the source files for instrumented tests in
module-name/src/androidTest/java/
. This directory already exists when you create a new project and contains an example instrumented test." —
developer.android.com/training/testing/instrumented-tests
Driven by
androidTestImplementation
. Runs via
./gradlew connectedAndroidTest
or
./gradlew connectedDebugAndroidTest
. Requires a connected device or emulator. Uses
AndroidJUnitRunner
per CORPUS §H.2.
The page is also explicit on the
testImplementation
vs
androidTestImplementation
split:
"Note:
testImplementation
adds dependencies for local tests and
androidTestImplementation
adds dependencies for Instrumented tests." —
developer.android.com/training/testing/local-tests
根据
/training/testing/instrumented-tests
:
“在 Android Studio 项目中,你将插桩测试的源文件存放在
module-name/src/androidTest/java/
中。该目录已经存在,并包含一个插桩测试示例。” —
developer.android.com/training/testing/instrumented-tests
由
androidTestImplementation
驱动。通过
./gradlew connectedAndroidTest
或
./gradlew connectedDebugAndroidTest
运行。需要连接设备或模拟器。根据 CORPUS §H.2,使用
AndroidJUnitRunner
。
该页面也明确说明了
testImplementation
与
androidTestImplementation
的区别:
“注意:
testImplementation
为本地测试添加依赖,
androidTestImplementation
为插桩测试添加依赖。” —
developer.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:
  • testImplementation
    — JVM (host) tests. Includes Mockito, MockK, Robolectric, kotlinx-coroutines-test, Turbine.
  • androidTestImplementation
    — instrumented (device) tests. Includes Espresso, UiAutomator, AndroidJUnitRunner, Compose
    ui-test-junit4
    .
  • debugImplementation
    — main
    debug
    variant. Used by
    androidx.compose.ui:ui-test-manifest
    and
    androidx.fragment:fragment-testing-manifest
    because the test APK is built on top of the debug APK and needs the manifest entries merged in.
androidx.compose.ui:ui-test-manifest
MUST go on
debugImplementation
, not
androidTestImplementation
— see
../../../compose/setup/configuring-test-dependencies/SKILL.md
for the lint check (
TestManifestGradleConfiguration
) that enforces this.
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)
Agent 必须区分清楚以下三种配置:
  • testImplementation
    ——JVM(主机)测试。适用于 Mockito、MockK、Robolectric、kotlinx-coroutines-test、Turbine。
  • androidTestImplementation
    ——插桩(设备)测试。适用于 Espresso、UiAutomator、AndroidJUnitRunner、Compose
    ui-test-junit4
    。
  • debugImplementation
    ——主
    debug
    variant。
    androidx.compose.ui:ui-test-manifest
    和
    androidx.fragment:fragment-testing-manifest
    需要使用此配置,因为测试 APK 构建于 debug APK 之上,并且需要合并相应的 manifest 条目。
androidx.compose.ui:ui-test-manifest
必须放在
debugImplementation
,不能放在
androidTestImplementation
——有关强制执行此规则的 lint 检查(
TestManifestGradleConfiguration
),请参阅
../../../compose/setup/configuring-test-dependencies/SKILL.md
。

src/sharedTest/
— community convention, NOT Google-documented

src/sharedTest/
——社区约定,并非 Google 文档说明的约定

Per
tasks/research/R8-android-fundamentals.md
:
src/sharedTest/
is not mentioned by name on any of the six in-scope
developer.android.com/training/testing/...
pages or on the fetched Hilt-testing / rules pages.
It originated in Google's own Architecture Blueprints sample and the Advanced Android Testing Codelab. The pattern uses Gradle
sourceSets
to inject the same Java/Kotlin folder into BOTH
test
and
androidTest
:
kotlin
// 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
androidx.test.ext.junit.runners.AndroidJUnit4
(which dispatches correctly in both environments per CORPUS §G.6).
Why 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
srcDir(...)
call. (The mode of failure is build-time refusal in AGP, not a runtime
LinkageError
.) Tracked at https://github.com/robolectric/robolectric/issues/7432 (Robolectric maintainer thread, with reproductions and AGP-version table). Many modules either:
  • Stopped sharing tests and accepted duplication.
  • Migrated to a separate Gradle sub-module (
    :core-testing
    ) that ships test helpers via
    testImplementation
    and
    androidTestImplementation
    .
  • Adopted KMP-style source set names (
    androidHostTest
    /
    androidDeviceTest
    ).
根据
tasks/research/R8-android-fundamentals.md
:
在六个纳入范围的
developer.android.com/training/testing/...
页面以及获取到的 Hilt 测试/rules 页面中,均未明确提及
src/sharedTest/
。
该约定源自 Google 自己的 Architecture Blueprints 示例和 Advanced Android Testing Codelab。它使用 Gradle
sourceSets
,将同一个 Java/Kotlin 目录同时注入
test
和
androidTest
:
kotlin
// 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 主机测试运行,也可在模拟器上将其作为高保真插桩测试运行。测试类使用
androidx.test.ext.junit.runners.AndroidJUnit4
,根据 CORPUS §G.6,该 runner 能在两种环境中正确分派测试。
它失效的原因:AGP 7.2+ 在构建时规定同一个源目录不能由多个源集共享——构建本身会直接拒绝,并报告与重复的
srcDir(...)
调用相关的错误。(失败形式是 AGP 在构建时拒绝执行,而不是运行时出现
LinkageError
。)相关问题记录于 https://github.com/robolectric/robolectric/issues/7432(Robolectric 维护者讨论线程,其中包含复现案例和 AGP 版本对照表)。许多模块采取了以下方式:
  • 停止共享测试并接受代码重复。
  • 迁移到独立的 Gradle 子模块(
    :core-testing
    ),通过
    testImplementation
    和
    androidTestImplementation
    提供测试辅助代码。
  • 采用 KMP 风格的源集名称(
    androidHostTest
    /
    androidDeviceTest
    )。

KMP-style
androidHostTest
/
androidDeviceTest

KMP 风格的
androidHostTest
/
androidDeviceTest

Compose 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:
compose/ui/ui-test/src/androidHostTest/kotlin/androidx/compose/ui/test/RobolectricComposeTest.kt
is a host (Robolectric) test, while
compose/material3/material3/src/androidDeviceTest/.../SwitchTest.kt
is a device test. Both compile against
commonTest
for shared helpers.
For 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 needed
The
:feature:home-testing
module hosts
FakeUserRepository
,
MainDispatcherRule
, custom matchers — anything both host and device tests want.
Alternative: AGP 7.0+
testFixtures
flag (
android { testFixtures { enable = true } }
), which exposes
testFixtures()
Gradle artifacts for
testFixturesImplementation
and is consumable from sibling modules'
testImplementation
/
androidTestImplementation
.
MUST NOT cite
developer.android.com/training/testing/...
for
sharedTest
— none of those pages document it. MUST cite the Architecture Blueprints repo or
tasks/research/R8-android-fundamentals.md
instead.
根据 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 中的实际证据:
compose/ui/ui-test/src/androidHostTest/kotlin/androidx/compose/ui/test/RobolectricComposeTest.kt
是主机(Robolectric)测试,而
compose/material3/material3/src/androidDeviceTest/.../SwitchTest.kt
是设备测试。两者都会针对
commonTest
中的共享辅助代码进行编译。
对于仅支持 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-testing
模块承载
FakeUserRepository
、
MainDispatcherRule
、自定义 matcher,以及主机测试和设备测试共同需要的其他内容。
另一种方案是使用 AGP 7.0+ 的
testFixtures
开关(
android { testFixtures { enable = true } }
)。它会公开
testFixtures()
Gradle artifact 和
testFixturesImplementation
,可供同级模块通过
testImplementation
/
androidTestImplementation
使用。
不得将
developer.android.com/training/testing/...
作为
sharedTest
的引用来源——这些页面均未记录该约定。应改为引用 Architecture Blueprints 仓库或
tasks/research/R8-android-fundamentals.md
。

File 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

模式:错误与正确——
testImplementation
与
androidTestImplementation

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")
}
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/
中使用 Robolectric

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
配置

kotlin
// 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
../../../compose/setup/configuring-test-dependencies/SKILL.md
for the lint detail.
kotlin
// 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.md
。

Pattern: AGP 7.2+
sharedTest
migration

模式:迁移 AGP 7.2+ 中的
sharedTest

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)
    }
}
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
    src/test/
    with
    testImplementation
    deps.
  • MUST put Robolectric tests in
    src/test/
    . Robolectric is a JVM Android simulator, not an instrumented runner.
  • MUST put real-device / emulator tests in
    src/androidTest/
    with
    androidTestImplementation
    deps.
  • MUST put
    androidx.compose.ui:ui-test-manifest
    and
    androidx.fragment:fragment-testing-manifest
    on
    debugImplementation
    , never
    androidTestImplementation
    .
  • MUST NOT cite
    developer.android.com/training/testing/...
    as the source for
    src/sharedTest/
    . It is not documented there. Cite the Architecture Blueprints repo or
    tasks/research/R8-android-fundamentals.md
    .
  • MUST NOT add Espresso, UiAutomator, or
    ui-test-junit4
    to
    testImplementation
    . They will compile but fail at runtime when no
    Instrumentation
    is present.
  • PREFERRED: for shared test helpers, extract a
    :core-testing
    Gradle sub-module or use
    android.testFixtures.enable = true
    rather than the AGP-7.2-fragile
    sharedTest
    source set.
  • PREFERRED: in KMP modules, follow Compose's lead —
    androidCommonTest
    for helpers,
    androidHostTest
    for Robolectric,
    androidDeviceTest
    for emulator tests.
  • PREFERRED: name backtick test methods freely in
    src/test/
    ; restrict to API 30+ devices in
    src/androidTest/
    per
    /training/testing/instrumented-tests
    .
  • 必须将纯 Kotlin / JVM 测试放在
    src/test/
    ,并使用
    testImplementation
    依赖。
  • 必须将 Robolectric 测试放在
    src/test/
    。Robolectric 是 JVM Android 模拟器,而不是插桩 runner。
  • 必须将真实设备或模拟器测试放在
    src/androidTest/
    ,并使用
    androidTestImplementation
    依赖。
  • 必须将
    androidx.compose.ui:ui-test-manifest
    和
    androidx.fragment:fragment-testing-manifest
    放在
    debugImplementation
    ,绝不能放在
    androidTestImplementation
    。
  • 不得将
    developer.android.com/training/testing/...
    作为
    src/sharedTest/
    的来源。这些页面并未记录该约定。应引用 Architecture Blueprints 仓库或
    tasks/research/R8-android-fundamentals.md
    。
  • 不得将 Espresso、UiAutomator 或
    ui-test-junit4
    添加到
    testImplementation
    。当环境中不存在
    Instrumentation
    时,它们虽然可以编译,但运行时必然失败。
  • **首选:**对于共享测试辅助代码,提取
    :core-testing
    Gradle 子模块或启用
    android.testFixtures.enable = true
    ,而不是使用容易被 AGP 7.2 破坏的
    sharedTest
    源集。
  • **首选:**在 KMP 模块中遵循 Compose 的做法——使用
    androidCommonTest
    存放辅助代码,使用
    androidHostTest
    运行 Robolectric 测试,使用
    androidDeviceTest
    运行模拟器测试。
  • **首选:**在
    src/test/
    中可以自由使用反引号包裹的测试方法名称;根据
    /training/testing/instrumented-tests
    ,在
    src/androidTest/
    中应仅将其用于 API 30+ 设备。

Verification

验证

  • No Robolectric test exists under
    src/androidTest/
    . Run
    find src/androidTest -name '*.kt' -exec grep -l 'org.robolectric' {} +
    ; expect empty output.
  • No Espresso / UiAutomator import exists under
    src/test/
    . Run
    find src/test -name '*.kt' -exec grep -l 'androidx.test.espresso\|androidx.test.uiautomator' {} +
    ; expect empty output.
  • androidx.compose.ui:ui-test-manifest
    is declared exactly on
    debugImplementation
    . Run
    ./gradlew :<module>:lint
    ; expect no
    TestManifestGradleConfiguration
    warning.
  • ./gradlew :<module>:testDebugUnitTest
    runs JVM tests without invoking
    connectedDebugAndroidTest
    .
  • ./gradlew :<module>:connectedDebugAndroidTest
    invokes only tests under
    src/androidTest/
    (verify with
    --info
    output).
  • If shared helpers exist, they live in a
    :core-testing
    sub-module, in
    testFixtures
    , or in
    androidCommonTest
    — never in a literal
    src/sharedTest/
    folder wired via
    sourceSets { ... srcDir(...) }
    .
  • testOptions.unitTests.isIncludeAndroidResources = true
    is set when any host test references
    R.*
    .
  • src/androidTest/
    下不存在 Robolectric 测试。运行
    find src/androidTest -name '*.kt' -exec grep -l 'org.robolectric' {} +
    ;预期无输出。
  • src/test/
    下不存在 Espresso / UiAutomator import。运行
    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
    警告。
  • ./gradlew :<module>:testDebugUnitTest
    可运行 JVM 测试,而不会调用
    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/
    ,
    testImplementation
    , "local test runs directly on your own workstation".
  • developer.android.com/training/testing/instrumented-tests
    —
    src/androidTest/
    ,
    androidTestImplementation
    , AndroidJUnitRunner, backtick caveat.
  • developer.android.com/training/testing/fundamentals
    — "Big local test: You can use an Android simulator that runs locally, such as Robolectric".
  • tasks/research/R8-android-fundamentals.md
    — verbatim quotes; documents that
    src/sharedTest/
    is NOT on any of the six in-scope
    /training/testing/...
    pages.
  • Architecture Blueprints (origin of the
    sharedTest
    pattern): https://github.com/android/architecture-samples
  • AGP source-set documentation: https://developer.android.com/build/build-variants#sourcesets
  • testFixtures
    flag: https://developer.android.com/build/dependencies#test-fixtures
  • CORPUS §C "Source set conventions (KMP)" — Compose's internal
    androidHostTest
    /
    androidDeviceTest
    layout.
  • compose/ui/ui-test/src/androidHostTest/kotlin/androidx/compose/ui/test/RobolectricComposeTest.kt
    — canonical host-test skeleton in androidx.
  • compose/material3/material3/src/androidDeviceTest/.../SwitchTest.kt
    — canonical device-test skeleton.
  • 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/
    、
    androidTestImplementation
    、AndroidJUnitRunner、反引号注意事项。
  • developer.android.com/training/testing/fundamentals
    ——“大型本地测试:可以使用在本地运行的 Android 模拟器,例如 Robolectric”。
  • tasks/research/R8-android-fundamentals.md
    ——原文引述;说明
    src/sharedTest/
    并未出现在六个纳入范围的
    /training/testing/...
    页面中。
  • Architecture Blueprints(
    sharedTest
    约定的起源):https://github.com/android/architecture-samples
  • AGP source set 文档:https://developer.android.com/build/build-variants#sourcesets
  • testFixtures
    开关:https://developer.android.com/build/dependencies#test-fixtures
  • CORPUS §C“Source set conventions (KMP)”——Compose 内部的
    androidHostTest
    /
    androidDeviceTest
    结构。
  • compose/ui/ui-test/src/androidHostTest/kotlin/androidx/compose/ui/test/RobolectricComposeTest.kt
    ——androidx 中典型的 host test 骨架。
  • compose/material3/material3/src/androidDeviceTest/.../SwitchTest.kt
    ——典型的 device test 骨架。
  • 同级 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
    。