configuring-junit4-on-android
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseConfiguring JUnit4 on Android — The Right Runner, Registry, and Matrix
在 Android 上配置 JUnit4——正确的 Runner、Registry 与依赖矩阵
Almost every "test suite is misconfigured" report boils down to one of three root causes: the wrong is imported, the wrong is imported, or the size-annotation / dispatcher plumbing is missing. This skill encodes the exact Gradle matrix from 1.7.0 onward, the canonical FQCNs, and the minimal pattern that androidx itself ships in .
AndroidJUnit4InstrumentationRegistryandroidx.test:coreMainDispatcherRuletestutils-ktx几乎每一份“测试套件配置错误”的报告,最终都可归结为三个根因之一:导入了错误的 、导入了错误的 ,或者缺少 size 注解与 dispatcher 接线。本 skill 固化了从 1.7.0 开始的准确 Gradle 依赖矩阵、规范的 FQCN,以及 androidx 自身在 中提供的最小 模式。
AndroidJUnit4InstrumentationRegistryandroidx.test:coretestutils-ktxMainDispatcherRuleWhen to use this skill
何时使用此 skill
- The user reports ,
Cannot resolve symbol AndroidJUnit4, or asks "whichAndroidJUnit4 is deprecatedshould I import".AndroidJUnit4 - The user reports from
IllegalStateException: No instrumentation registeredin a unit test, or asks whyInstrumentationRegistry.getInstrumentation()is crossed out.InstrumentationRegistry - The user wants Truth subjects (,
IntentSubject,BundleSubject,LocationSubject) but does not know which artifact ships them.ParcelableSubject - The user wants to filter tests and asks how to wire
am instrument -e size small/@SmallTest/@MediumTest.@LargeTest - The user is writing a / coroutine test and needs the canonical
ViewModeltemplate.MainDispatcherRule
- 用户报告 、
Cannot resolve symbol AndroidJUnit4,或询问“应该导入哪个AndroidJUnit4 is deprecated”。AndroidJUnit4 - 用户在单元测试中调用 时遇到
InstrumentationRegistry.getInstrumentation(),或询问为什么IllegalStateException: No instrumentation registered被标记为废弃。InstrumentationRegistry - 用户需要 Truth subjects(、
IntentSubject、BundleSubject、LocationSubject),但不知道它们由哪个 artifact 提供。ParcelableSubject - 用户希望通过 过滤测试,并询问如何接入
am instrument -e size small/@SmallTest/@MediumTest。@LargeTest - 用户正在编写 或 coroutine 测试,需要规范的
ViewModel模板。MainDispatcherRule
When NOT to use this skill
何时不应使用此 skill
- The user is wiring Mockito mocks — use .
../../mocking/mocking-with-mockito/SKILL.md - The user is wiring MockK mocks — use .
../../mocking/mocking-with-mockk/SKILL.md - The user is configuring or
runTest { … }— useTurbineor../../coroutines/testing-coroutines-with-runtest/SKILL.md.../../coroutines/testing-flows-with-turbine/SKILL.md - The user is configuring Robolectric specifically (SDK matrix, resources, ) — use
@Config.../../robolectric/using-robolectric-correctly/SKILL.md - The user is running tests on a device with — use
am instrument.../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - The user is choosing between fakes and mocks — use .
../../../fundamentals/doubles/picking-test-doubles/SKILL.md
- 用户正在配置 Mockito mocks——请使用 。
../../mocking/mocking-with-mockito/SKILL.md - 用户正在配置 MockK mocks——请使用 。
../../mocking/mocking-with-mockk/SKILL.md - 用户正在配置 或
runTest { … }——请使用Turbine或../../coroutines/testing-coroutines-with-runtest/SKILL.md。../../coroutines/testing-flows-with-turbine/SKILL.md - 用户专门在配置 Robolectric(SDK 矩阵、资源、)——请使用
@Config。../../robolectric/using-robolectric-correctly/SKILL.md - 用户正在设备上使用 运行测试——请使用
am instrument。../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - 用户正在选择 fake 还是 mock——请使用 。
../../../fundamentals/doubles/picking-test-doubles/SKILL.md
Prerequisites
前置条件
- Android Gradle Plugin applied (or
com.android.application).com.android.library - A source set on disk (Gradle creates it lazily —
src/test/if missing).mkdir -p src/test/kotlin - Kotlin module (these notes assume Kotlin; the same FQCNs work from Java).
- For coroutine-related tests, already on the classpath.
org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.x
- 已应用 Android Gradle Plugin(或
com.android.application)。com.android.library - 磁盘上存在 source set(Gradle 会延迟创建它——如不存在,请执行
src/test/)。mkdir -p src/test/kotlin - Kotlin module(这些说明以 Kotlin 为例;同样的 FQCN 也可用于 Java)。
- 对于 coroutine 相关测试,classpath 中已经包含 。
org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.x
Workflow
工作流
- 1. Pin the canonical Gradle dependency matrix. These are the released stable versions backing this skill (verified against ). Pin them directly, do not
~/.gradle/caches/modules-2/files-2.1/androidx.test/...:latest.release
kotlin
dependencies {
// Core JUnit4
testImplementation("junit:junit:4.13.2")
// androidx.test foundations (work in src/test/ via Robolectric and in src/androidTest/)
testImplementation("androidx.test:core:1.7.0")
testImplementation("androidx.test:core-ktx:1.6.1")
testImplementation("androidx.test:runner:1.7.0")
testImplementation("androidx.test:rules:1.7.0")
testImplementation("androidx.test.ext:junit:1.3.0")
testImplementation("androidx.test.ext:junit-ktx:1.3.0")
testImplementation("androidx.test.ext:truth:1.7.0")
testImplementation("com.google.truth:truth:1.4.4")
// Coroutines test (for MainDispatcherRule / runTest)
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.1")
}For instrumented tests in , mirror the same artifacts on . The artifacts are dual-classpath compatible.
src/androidTest/androidTestImplementation- 2. Annotate test classes with the correct . There are TWO classes named
@RunWithon the classpath. The deprecated one isAndroidJUnit4(fileandroidx.test.runner.AndroidJUnit4L41-44 —runner-1.7.0/androidx/test/runner/AndroidJUnit4.java). The canonical one is@Deprecatedfrom theandroidx.test.ext.junit.runners.AndroidJUnit4artifact (fileandroidx.test.ext:junit:1.3.0L49). It delegates to Robolectric on the JVM (whenjunit-1.3.0/androidx/test/ext/junit/runners/AndroidJUnit4.javais on the classpath) and toorg.robolectric.RobolectricTestRunneron a device.androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
kotlin
import androidx.test.ext.junit.runners.AndroidJUnit4 // canonical
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MyTest { /* ... */ }- 3. Use the canonical .
InstrumentationRegistry(noandroidx.test.InstrumentationRegistry) is.platform.app.since@Deprecated1.x — every member is:monitor'd to its replacement. The canonical class is@InlineMe(fileandroidx.test.platform.app.InstrumentationRegistryL30-85).monitor-1.8.0/androidx/test/platform/app/InstrumentationRegistry.java
kotlin
import androidx.test.platform.app.InstrumentationRegistry
val instrumentation = InstrumentationRegistry.getInstrumentation()
val args: Bundle = InstrumentationRegistry.getArguments() // copy of -e key/value pairsgetInstrumentation()IllegalStateException("No instrumentation registered! Must run under a registering instrumentation.")Instrumentationsrc/test/@RunWith(AndroidJUnit4::class)- 4. Pull the application Context via , not via the registry.
ApplicationProvideris the single entry point for the Application context (fileApplicationProvider.getApplicationContext()L29-43). Internally it returnscore-1.7.0/androidx/test/core/app/ApplicationProvider.java— same Context, more readable callsite, and the unchecked generic lets callers cast to theirgetInstrumentation().getTargetContext().getApplicationContext()subclass.Application
kotlin
import androidx.test.core.app.ApplicationProvider
val ctx: Context = ApplicationProvider.getApplicationContext()
val app: MyApp = ApplicationProvider.getApplicationContext() // unchecked cast- 5. Tag each test with a size annotation when the suite is large enough to need filtering. Size is one of three: (
@SmallTest, no Android stubs),<200ms(@MediumTest, Android framework via Robolectric),<1000ms(@LargeTest, instrumented). Annotations live in>1000ms(fileandroidx.test.filters.*L44-46). The runner'srunner-1.7.0/androidx/test/filters/SmallTest.java(RunnerArgs.SIZEL58) wiresrunner-1.7.0/androidx/test/internal/runner/RunnerArgs.javadirectly to these annotations.-e size <value>
kotlin
import androidx.test.filters.SmallTest
import androidx.test.filters.MediumTest
@SmallTest
class FastValidatorTest { /* ... */ }
@MediumTest
class RoomDaoTest { /* ... */ }The corresponding invocation is . See for the on-device counterpart.
am instrumentadb shell am instrument -w -r -e size small <pkg>/androidx.test.runner.AndroidJUnitRunner../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md- 6. Reach for Truth subjects from for Android-domain assertions. Truth shipped with
androidx.test.ext:truthadds Android-awareandroidx.test.ext:truth:1.7.0types. Each exposes aSubjectshortcut and astatic assertThat(T actual)factory:static Subject.Factory<T, S> name()
| Subject | FQCN package | Asserts on |
|---|---|---|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
Idiomatic import-and-call:
kotlin
import androidx.test.ext.truth.content.IntentSubject.assertThat
import androidx.test.ext.truth.os.BundleSubject
@Test fun intent_routes_to_settings() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("settings://wifi"))
assertThat(intent).hasAction(Intent.ACTION_VIEW)
assertThat(intent).hasData(Uri.parse("settings://wifi"))
}- 7. Install a for any test that touches
MainDispatcherRule. Compose,Dispatchers.Main, andviewModelScopeall default toLiveData, which is unavailable on the JVM unless swapped. The canonical androidx pattern lives atDispatchers.Main— use it verbatim:testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt
kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
val testDispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) {
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description) {
Dispatchers.resetMain()
}
}Apply on a test class:
kotlin
@RunWith(AndroidJUnit4::class)
class MyViewModelTest {
@get:Rule val mainDispatcherRule = MainDispatcherRule()
@Test fun loadsUsers() = runTest {
val vm = MyViewModel(repo = FakeUserRepository())
vm.load()
advanceUntilIdle()
assertThat(vm.users.value).isNotEmpty()
}
}StandardTestDispatcherrunCurrent()advanceUntilIdle()kotlinx.coroutines.test.runTestUnconfinedTestDispatcher- 8. Verify the test class actually runs. Execute the suite once: . The Gradle output shows the runner choice —
./gradlew :<module>:testDebugUnitTest --tests com.example.MyTestconfirms the canonical runner is bound;org.junit.runner.RunWith: AndroidJUnit4near the top confirms Robolectric is wiring up.Test process exited with status code
- 1. 固定规范的 Gradle 依赖矩阵。 以下是支撑此 skill 的已发布稳定版本(已根据 验证)。请直接固定这些版本,不要使用
~/.gradle/caches/modules-2/files-2.1/androidx.test/...:latest.release
kotlin
dependencies {
// Core JUnit4
testImplementation("junit:junit:4.13.2")
// androidx.test foundations (work in src/test/ via Robolectric and in src/androidTest/)
testImplementation("androidx.test:core:1.7.0")
testImplementation("androidx.test:core-ktx:1.6.1")
testImplementation("androidx.test:runner:1.7.0")
testImplementation("androidx.test:rules:1.7.0")
testImplementation("androidx.test.ext:junit:1.3.0")
testImplementation("androidx.test.ext:junit-ktx:1.3.0")
testImplementation("androidx.test.ext:truth:1.7.0")
testImplementation("com.google.truth:truth:1.4.4")
// Coroutines test (for MainDispatcherRule / runTest)
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.1")
}对于 中的 instrumented tests,请在 中使用相同的 artifacts。这些 artifacts 同时兼容两类 classpath。
src/androidTest/androidTestImplementation- 2. 使用正确的 标注测试类。 classpath 中有两个名为
@RunWith的类。已弃用的一个是AndroidJUnit4(文件androidx.test.runner.AndroidJUnit4L41-44——runner-1.7.0/androidx/test/runner/AndroidJUnit4.java)。规范的类是来自@Deprecatedartifact 的androidx.test.ext:junit:1.3.0(文件androidx.test.ext.junit.runners.AndroidJUnit4L49)。在 JVM 上,当 classpath 中存在junit-1.3.0/androidx/test/ext/junit/runners/AndroidJUnit4.java时,它会委托给 Robolectric;在设备上,则委托给org.robolectric.RobolectricTestRunner。androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
kotlin
import androidx.test.ext.junit.runners.AndroidJUnit4 // canonical
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MyTest { /* ... */ }- 3. 使用规范的 。
InstrumentationRegistry(没有androidx.test.InstrumentationRegistry)从.platform.app.1.x 起已是:monitor——它的每个成员都通过@Deprecated迁移到了替代 API。规范的类是@InlineMe(文件androidx.test.platform.app.InstrumentationRegistryL30-85)。monitor-1.8.0/androidx/test/platform/app/InstrumentationRegistry.java
kotlin
import androidx.test.platform.app.InstrumentationRegistry
val instrumentation = InstrumentationRegistry.getInstrumentation()
val args: Bundle = InstrumentationRegistry.getArguments() // copy of -e key/value pairs如果在 instrumentation host 之外调用,或在 Robolectric 初始化其 shadow 之前调用, 会抛出 。Robolectric 会在测试运行前向 registry 注册一个 实例,因此当启用 时,这段代码在 中可以正常工作。
getInstrumentation()IllegalStateException("No instrumentation registered! Must run under a registering instrumentation.")Instrumentation@RunWith(AndroidJUnit4::class)src/test/- 4. 通过 获取 Application Context,而不是通过 registry。
ApplicationProvider是获取 Application context 的统一入口(文件ApplicationProvider.getApplicationContext()L29-43)。它在内部返回core-1.7.0/androidx/test/core/app/ApplicationProvider.java——得到的是同一个 Context,但调用处更清晰;其 unchecked generic 允许调用方转换为自己的getInstrumentation().getTargetContext().getApplicationContext()子类。Application
kotlin
import androidx.test.core.app.ApplicationProvider
val ctx: Context = ApplicationProvider.getApplicationContext()
val app: MyApp = ApplicationProvider.getApplicationContext() // unchecked cast- 5. 当测试套件规模较大、需要过滤时,为每个测试添加 size 注解。 Size 共分为三种:(
@SmallTest,不依赖 Android stubs)、<200ms(@MediumTest,通过 Robolectric 使用 Android framework)和<1000ms(@LargeTest,instrumented)。这些注解位于>1000ms(文件androidx.test.filters.*L44-46)。Runner 的runner-1.7.0/androidx/test/filters/SmallTest.java(RunnerArgs.SIZEL58)会将runner-1.7.0/androidx/test/internal/runner/RunnerArgs.java直接接入这些注解。-e size <value>
kotlin
import androidx.test.filters.SmallTest
import androidx.test.filters.MediumTest
@SmallTest
class FastValidatorTest { /* ... */ }
@MediumTest
class RoomDaoTest { /* ... */ }对应的 调用方式为 。设备端用法请参阅 。
am instrumentadb shell am instrument -w -r -e size small <pkg>/androidx.test.runner.AndroidJUnitRunner../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md- 6. 针对 Android 领域的断言,使用 提供的 Truth subjects。 Truth 随
androidx.test.ext:truth一起提供 Android-awareandroidx.test.ext:truth:1.7.0类型。每个类型都公开一个Subject快捷方法和一个static assertThat(T actual)factory:static Subject.Factory<T, S> name()
| Subject | FQCN package | 断言对象 |
|---|---|---|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
惯用的导入和调用方式:
kotlin
import androidx.test.ext.truth.content.IntentSubject.assertThat
import androidx.test.ext.truth.os.BundleSubject
@Test fun intent_routes_to_settings() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("settings://wifi"))
assertThat(intent).hasAction(Intent.ACTION_VIEW)
assertThat(intent).hasData(Uri.parse("settings://wifi"))
}- 7. 为任何涉及 的测试安装
Dispatchers.Main。 Compose、MainDispatcherRule和viewModelScope默认都使用LiveData;如果不进行替换,它在 JVM 上不可用。规范的 androidx 模式位于Dispatchers.Main——请原样使用:testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt
kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
val testDispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) {
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description) {
Dispatchers.resetMain()
}
}在测试类上应用:
kotlin
@RunWith(AndroidJUnit4::class)
class MyViewModelTest {
@get:Rule val mainDispatcherRule = MainDispatcherRule()
@Test fun loadsUsers() = runTest {
val vm = MyViewModel(repo = FakeUserRepository())
vm.load()
advanceUntilIdle()
assertThat(vm.users.value).isNotEmpty()
}
}应优先使用 ——它会排队保存 continuation,仅在调用 / 时推进,与 语义一致。 会立即调度,仅在执行顺序无关紧要时才适合使用。
StandardTestDispatcherrunCurrent()advanceUntilIdle()kotlinx.coroutines.test.runTestUnconfinedTestDispatcher- 8. 确认测试类确实已运行。 执行一次测试套件:。Gradle 输出会显示所选用的 runner——
./gradlew :<module>:testDebugUnitTest --tests com.example.MyTest表明已绑定规范的 runner;顶部附近的org.junit.runner.RunWith: AndroidJUnit4则表明 Robolectric 已完成接线。Test process exited with status code
Patterns
模式
Pattern: WRONG vs RIGHT — choosing the AndroidJUnit4
runner
AndroidJUnit4模式:错误与正确——选择 AndroidJUnit4
runner
AndroidJUnit4kotlin
// WRONG
import org.junit.runners.JUnit4
import org.junit.runner.RunWith
@RunWith(JUnit4::class)
class MyTest { /* uses InstrumentationRegistry, ApplicationProvider, ... */ }
// WRONG because: stock JUnit4 does not register the Android `Instrumentation` instance
// into InstrumentationRegistry. ApplicationProvider.getApplicationContext() throws
// IllegalStateException("No instrumentation registered!"). Robolectric is also never
// activated even when on the classpath, so all framework calls hit unmocked stubs.kotlin
// RIGHT
import androidx.test.ext.junit.runners.AndroidJUnit4 // ext.junit.runners, NOT runner.AndroidJUnit4
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MyTest { /* ... */ }The deprecated alias still compiles but emits an unsuppressed deprecation warning. New code MUST import from .
androidx.test.runner.AndroidJUnit4androidx.test.ext.junit.runnerskotlin
// WRONG
import org.junit.runners.JUnit4
import org.junit.runner.RunWith
@RunWith(JUnit4::class)
class MyTest { /* uses InstrumentationRegistry, ApplicationProvider, ... */ }
// WRONG because: stock JUnit4 does not register the Android `Instrumentation` instance
// into InstrumentationRegistry. ApplicationProvider.getApplicationContext() throws
// IllegalStateException("No instrumentation registered!"). Robolectric is also never
// activated even when on the classpath, so all framework calls hit unmocked stubs.kotlin
// RIGHT
import androidx.test.ext.junit.runners.AndroidJUnit4 // ext.junit.runners, NOT runner.AndroidJUnit4
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MyTest { /* ... */ }已弃用的别名 仍可编译,但会产生未抑制的 deprecation warning。新代码必须从 导入。
androidx.test.runner.AndroidJUnit4androidx.test.ext.junit.runnersPattern: WRONG vs RIGHT — InstrumentationRegistry
import
InstrumentationRegistry模式:错误与正确——InstrumentationRegistry
导入
InstrumentationRegistrykotlin
// WRONG
import androidx.test.InstrumentationRegistry // @Deprecated since :monitor
val ctx = InstrumentationRegistry.getContext() // also deprecated — not the Application context
// WRONG because: every member of androidx.test.InstrumentationRegistry is @Deprecated
// and @InlineMe'd to its replacement. getContext() returns the instrumentation package
// context, NOT the Application context — common source of "resource not found" failures.kotlin
// RIGHT
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.core.app.ApplicationProvider
val ctx: Context = ApplicationProvider.getApplicationContext() // application context
val args: Bundle = InstrumentationRegistry.getArguments() // -e key/value pairs
val instr = InstrumentationRegistry.getInstrumentation()kotlin
// WRONG
import androidx.test.InstrumentationRegistry // @Deprecated since :monitor
val ctx = InstrumentationRegistry.getContext() // also deprecated — not the Application context
// WRONG because: every member of androidx.test.InstrumentationRegistry is @Deprecated
// and @InlineMe'd to its replacement. getContext() returns the instrumentation package
// context, NOT the Application context — common source of "resource not found" failures.kotlin
// RIGHT
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.core.app.ApplicationProvider
val ctx: Context = ApplicationProvider.getApplicationContext() // application context
val args: Bundle = InstrumentationRegistry.getArguments() // -e key/value pairs
val instr = InstrumentationRegistry.getInstrumentation()Pattern: WRONG vs RIGHT — accessing Compose Dispatchers.Main
from a unit test
Dispatchers.Main模式:错误与正确——在单元测试中访问 Compose Dispatchers.Main
Dispatchers.Mainkotlin
// WRONG
class MyViewModelTest {
@Test fun loadsUsers() = runBlocking {
val vm = MyViewModel(repo = FakeUserRepository())
vm.load()
// Throws IllegalStateException: "Module with the Main dispatcher is missing"
}
}
// WRONG because: kotlinx-coroutines-android (the Main dispatcher impl for Android) is
// NOT on the unit-test classpath. Without Dispatchers.setMain(...), any viewModelScope or
// LaunchedEffect that touches the Main dispatcher fails immediately.kotlin
// RIGHT
class MyViewModelTest {
@get:Rule val mainDispatcherRule = MainDispatcherRule()
@Test fun loadsUsers() = runTest {
val vm = MyViewModel(repo = FakeUserRepository())
vm.load()
advanceUntilIdle()
assertThat(vm.users.value).hasSize(2)
}
}kotlin
// WRONG
class MyViewModelTest {
@Test fun loadsUsers() = runBlocking {
val vm = MyViewModel(repo = FakeUserRepository())
vm.load()
// Throws IllegalStateException: "Module with the Main dispatcher is missing"
}
}
// WRONG because: kotlinx-coroutines-android (the Main dispatcher impl for Android) is
// NOT on the unit-test classpath. Without Dispatchers.setMain(...), any viewModelScope or
// LaunchedEffect that touches the Main dispatcher fails immediately.kotlin
// RIGHT
class MyViewModelTest {
@get:Rule val mainDispatcherRule = MainDispatcherRule()
@Test fun loadsUsers() = runTest {
val vm = MyViewModel(repo = FakeUserRepository())
vm.load()
advanceUntilIdle()
assertThat(vm.users.value).hasSize(2)
}
}Pattern: filtering by size from the command line
模式:从命令行按 size 过滤
The / / annotations bind directly to ( L58). For instrumented tests:
@SmallTest@MediumTest@LargeTestRunnerArgs.SIZErunner-1.7.0/androidx/test/internal/runner/RunnerArgs.javabash
adb shell am instrument -w -r -e size small \
com.example.test/androidx.test.runner.AndroidJUnitRunnerFor Robolectric-on-JVM tests, Gradle property filtering is the standard route:
bash
./gradlew :app:testDebugUnitTest --tests "com.example.*" \
-PandroidTestSize=smallCombined with (the arg, L60) you get composable filtering.
-e annotation com.example.SmokeTestRunnerArgs.ANNOTATION@SmallTest@MediumTest@LargeTestRunnerArgs.SIZErunner-1.7.0/androidx/test/internal/runner/RunnerArgs.javabash
adb shell am instrument -w -r -e size small \
com.example.test/androidx.test.runner.AndroidJUnitRunner对于运行在 JVM 上的 Robolectric tests,标准做法是使用 Gradle property 进行过滤:
bash
./gradlew :app:testDebugUnitTest --tests "com.example.*" \
-PandroidTestSize=small将其与 ( 参数,L60)结合使用,即可组合过滤条件。
-e annotation com.example.SmokeTestRunnerArgs.ANNOTATIONMandatory rules
强制规则
- MUST import from
AndroidJUnit4. MUST NOT importandroidx.test.ext.junit.runners— it isandroidx.test.runner.AndroidJUnit4.@Deprecated - MUST import from
InstrumentationRegistry. MUST NOT importandroidx.test.platform.app— it isandroidx.test.InstrumentationRegistry.@Deprecated - MUST use for the Application context. MUST NOT call
ApplicationProvider.getApplicationContext()directly —InstrumentationRegistry.getInstrumentation().getTargetContext()is the canonical entry point and handles the unchecked cast.ApplicationProvider - MUST install a (or equivalent
MainDispatcherRule/Dispatchers.setMainplumbing) before any test that touchesresetMain,viewModelScope, or anyLaunchedEffectconsumer. Without it, the test crashes withDispatchers.Main.IllegalStateException: Module with the Main dispatcher is missing - MUST prefer over
StandardTestDispatcherinUnconfinedTestDispatcher.MainDispatcherRulematchesStandardTestDispatchersemantics; eager dispatch is a footgun for ordering.runTest - MUST annotate every test class or method with exactly ONE size annotation (/
@SmallTest/@MediumTest) when the suite is filtered by size. Multiple size annotations on the same target produce undefined runner behaviour.@LargeTest - MUST pin Robolectric independently — it does not ship in the androidx-test BOM. Use matching the
org.robolectric:robolectric:4.xof the module.compileSdk - MUST NOT use in new code — it is
runBlockingTest { }since@Deprecated(level = DeprecationLevel.ERROR)1.7. Usekotlinx-coroutines-testinstead.runTest { } - MUST NOT use — it is
ActivityTestRule<A>. Use@Deprecatedinstead (androidx.test.ext.junit.rules.ActivityScenarioRule<A>L56). For instrumented variants, seejunit-1.3.0/androidx/test/ext/junit/rules/ActivityScenarioRule.java.../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - PREFERRED: declare in the module's
testOptions.unitTests.isIncludeAndroidResources = trueblock. Robolectric needs merged resources to inflate any layout or readandroid { … }.R.string.*
- 必须从 导入
androidx.test.ext.junit.runners。不得导入AndroidJUnit4——后者已标记为androidx.test.runner.AndroidJUnit4。@Deprecated - 必须从 导入
androidx.test.platform.app。不得导入InstrumentationRegistry——后者已标记为androidx.test.InstrumentationRegistry。@Deprecated - 必须使用 获取 Application context。不得直接调用
ApplicationProvider.getApplicationContext()——InstrumentationRegistry.getInstrumentation().getTargetContext()是规范入口,并会处理 unchecked cast。ApplicationProvider - 必须在任何涉及 、
viewModelScope或其他LaunchedEffectconsumer 的测试之前安装Dispatchers.Main(或等效的MainDispatcherRule/Dispatchers.setMain接线)。否则测试会因resetMain而崩溃。IllegalStateException: Module with the Main dispatcher is missing - 必须在 中优先使用
MainDispatcherRule,而不是StandardTestDispatcher。UnconfinedTestDispatcher与StandardTestDispatcher语义一致;eager dispatch 容易导致执行顺序问题。runTest - 必须在按 size 过滤的测试套件中,为每个测试类或测试方法添加恰好一个 size 注解(/
@SmallTest/@MediumTest)。同一目标上存在多个 size 注解会产生未定义的 runner 行为。@LargeTest - 必须单独固定 Robolectric 版本——它不包含在 androidx-test BOM 中。请使用与 module 的 匹配的
compileSdk。org.robolectric:robolectric:4.x - 不得在新代码中使用 ——从
runBlockingTest { }1.7 起,它已被标记为kotlinx-coroutines-test。请改用@Deprecated(level = DeprecationLevel.ERROR)。runTest { } - 不得使用 ——它已废弃。请改用
ActivityTestRule<A>(androidx.test.ext.junit.rules.ActivityScenarioRule<A>L56)。关于 instrumented variants,请参阅junit-1.3.0/androidx/test/ext/junit/rules/ActivityScenarioRule.java。../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - **优先:**在 module 的 块中声明
android { … }。Robolectric 需要合并后的 resources,才能 inflate layout 或读取testOptions.unitTests.isIncludeAndroidResources = true。R.string.*
Verification
验证
- compiles and reports
./gradlew :<module>:testDebugUnitTestfor the new suite.Tests run: N, Failures: 0 - returns NO matches (only
grep -r "import androidx.test.runner.AndroidJUnit4" src/test src/androidTestis allowed).androidx.test.ext.junit.runners.AndroidJUnit4 - returns NO matches.
grep -r "import androidx.test.InstrumentationRegistry" src/test src/androidTest - Any test that uses /
viewModelScopedeclaresDispatchers.Mainand uses@get:Rule val mainDispatcherRule = MainDispatcherRule().runTest { … } - At least one test class is annotated with ,
@SmallTest, or@MediumTestif the suite is meant to be filtered.@LargeTest - output shows
./gradlew :<module>:testDebugUnitTest --info(host) ororg.robolectric.RobolectricTestRunner(device) in the runner stack — confirming theAndroidJUnit4ClassRunnerdelegate selection.AndroidJUnit4
- 可以编译,并为新测试套件报告
./gradlew :<module>:testDebugUnitTest。Tests run: N, Failures: 0 - 无匹配项(只允许使用
grep -r "import androidx.test.runner.AndroidJUnit4" src/test src/androidTest)。androidx.test.ext.junit.runners.AndroidJUnit4 - 无匹配项。
grep -r "import androidx.test.InstrumentationRegistry" src/test src/androidTest - 任何使用 /
viewModelScope的测试都声明了Dispatchers.Main,并使用@get:Rule val mainDispatcherRule = MainDispatcherRule()。runTest { … } - 如果测试套件需要按 size 过滤,至少有一个测试类标注了 、
@SmallTest或@MediumTest。@LargeTest - 的输出在 runner stack 中显示
./gradlew :<module>:testDebugUnitTest --info(host)或org.robolectric.RobolectricTestRunner(device),从而确认AndroidJUnit4ClassRunnerdelegate 的选择结果。AndroidJUnit4
References
参考资料
- AndroidX Test releases: https://developer.android.com/jetpack/androidx/releases/test
- Local tests guide: https://developer.android.com/training/testing/local-tests
- Instrumented tests guide: https://developer.android.com/training/testing/instrumented-tests
- AndroidJUnitRunner reference: https://developer.android.com/training/testing/junit-runner
- Truth subject reference (upstream tree): https://github.com/android/android-test/tree/main/ext/truth/java/androidx/test/ext/truth
- (L41-44) —
runner-1.7.0/androidx/test/runner/AndroidJUnit4.javaalias.@Deprecated - (L49-70) — canonical runner with Robolectric/Android delegate selection.
junit-1.3.0/androidx/test/ext/junit/runners/AndroidJUnit4.java - (L30-85) — canonical registry;
monitor-1.8.0/androidx/test/platform/app/InstrumentationRegistry.java,getInstrumentation,getArguments.registerInstance - (L34) —
monitor-1.8.0/androidx/test/InstrumentationRegistry.javalegacy registry.@Deprecated - (L29-43) — single-method facade returning the Application context.
core-1.7.0/androidx/test/core/app/ApplicationProvider.java - (L44-46),
runner-1.7.0/androidx/test/filters/SmallTest.java,MediumTest.java— size annotation definitions.LargeTest.java - (L54-99) — every
runner-1.7.0/androidx/test/internal/runner/RunnerArgs.javaargument the runner accepts, including-e <key> <value>,size,annotation,class,package/numShards.shardIndex - — canonical androidx
testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.ktsource, identical pattern shipped here.MainDispatcherRule - Cross-set: — the framework-agnostic
../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.mdassertions (kotlin.test,assertEquals,assertFailsWith) used inside these JUnit4 tests; also the only assertion API available in@BeforeTest.commonTest
- AndroidX Test releases:https://developer.android.com/jetpack/androidx/releases/test
- Local tests guide:https://developer.android.com/training/testing/local-tests
- Instrumented tests guide:https://developer.android.com/training/testing/instrumented-tests
- AndroidJUnitRunner reference:https://developer.android.com/training/testing/junit-runner
- Truth subject reference(upstream tree):https://github.com/android/android-test/tree/main/ext/truth/java/androidx/test/ext/truth
- (L41-44)——
runner-1.7.0/androidx/test/runner/AndroidJUnit4.java别名。@Deprecated - (L49-70)——规范 runner,包含 Robolectric/Android delegate 选择逻辑。
junit-1.3.0/androidx/test/ext/junit/runners/AndroidJUnit4.java - (L30-85)——规范 registry;包含
monitor-1.8.0/androidx/test/platform/app/InstrumentationRegistry.java、getInstrumentation、getArguments。registerInstance - (L34)——已废弃的 legacy registry。
monitor-1.8.0/androidx/test/InstrumentationRegistry.java - (L29-43)——返回 Application context 的单方法 facade。
core-1.7.0/androidx/test/core/app/ApplicationProvider.java - (L44-46)、
runner-1.7.0/androidx/test/filters/SmallTest.java、MediumTest.java——size 注解定义。LargeTest.java - (L54-99)——runner 接受的所有
runner-1.7.0/androidx/test/internal/runner/RunnerArgs.java参数,包括-e <key> <value>、size、annotation、class、package/numShards。shardIndex - ——规范 androidx
testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt源码,与此处提供的模式相同。MainDispatcherRule - Cross-set:——这些 JUnit4 测试中使用的 framework-agnostic
../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.mdassertions(kotlin.test、assertEquals、assertFailsWith);也是在@BeforeTest中唯一可用的 assertion API。commonTest