migrating-from-android-test-classes

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Migrating Off android.test.* — From the Platform's Legacy Test Classes to AndroidX Test

停止使用
android.test.*
——从平台旧版测试类迁移到 AndroidX Test

The
android.test.*
package shipped in the Android SDK (
InstrumentationTestCase
,
ActivityInstrumentationTestCase2
,
AndroidTestCase
,
ServiceTestCase
,
MoreAsserts
,
TouchUtils
,
android.test.mock.*
, …) is
@Deprecated
— the platform's own Javadoc routes every class to AndroidX Test. Old codebases still carry these, and they actively hold back JUnit4, Espresso,
ActivityScenario
, and the AndroidX runner. This skill is the class-by-class replacement map and the mechanical migration patterns.
Android SDK 中随附的
android.test.*
包(
InstrumentationTestCase
、
ActivityInstrumentationTestCase2
、
AndroidTestCase
、
ServiceTestCase
、
MoreAsserts
、
TouchUtils
、
android.test.mock.*
等)已标记为
@Deprecated
——平台自身的 Javadoc 都会将每个类指向 AndroidX Test。旧代码库中仍保留着这些类,而它们实际上会阻碍采用 JUnit4、Espresso、
ActivityScenario
和 AndroidX runner。本 skill 提供逐类别的替换映射和机械化迁移模式。

When to use this skill

何时使用此 skill

  • The IDE flags
    android.test.InstrumentationTestCase
    /
    AndroidTestCase
    /
    ActivityInstrumentationTestCase2
    /
    ServiceTestCase
    /
    MoreAsserts
    /
    ViewAsserts
    /
    TouchUtils
    /
    android.test.mock.*
    as
    @Deprecated
    .
  • A module's
    testInstrumentationRunner
    is
    android.test.InstrumentationTestRunner
    and tests behave oddly under
    AndroidJUnitRunner
    (or won't be discovered).
  • The user asks how to replace a specific legacy base class: "
    getInstrumentation()
    outside a
    TestCase
    ", "
    getActivity()
    /
    setActivityIntent()
    without
    ActivityInstrumentationTestCase2
    ", "
    getContext()
    without
    AndroidTestCase
    ".
  • A test extends
    junit.framework.TestCase
    (JUnit3 style:
    setUp()
    override,
    testFoo()
    naming,
    assertEquals
    from
    junit.framework.Assert
    ) and the team wants JUnit4.
  • The user mentions
    MoreAsserts.assertContentsInAnyOrder
    /
    assertEquals(int[], int[])
    /
    assertContainsRegex
    ,
    ViewAsserts.assertOnScreen
    ,
    TouchUtils.tapView
    /
    dragQuarterScreenDown
    , or
    android.test.suitebuilder.annotation.SmallTest
    .
  • IDE 将
    android.test.InstrumentationTestCase
    /
    AndroidTestCase
    /
    ActivityInstrumentationTestCase2
    /
    ServiceTestCase
    /
    MoreAsserts
    /
    ViewAsserts
    /
    TouchUtils
    /
    android.test.mock.*
    标记为
    @Deprecated
    。
  • 某模块的
    testInstrumentationRunner
    是
    android.test.InstrumentationTestRunner
    ,且测试在
    AndroidJUnitRunner
    下表现异常(或无法被发现)。
  • 用户询问如何替换特定的旧版基类:“在
    TestCase
    之外使用
    getInstrumentation()
    ”、“不使用
    ActivityInstrumentationTestCase2
    时如何调用
    getActivity()
    /
    setActivityIntent()
    ”、“不使用
    AndroidTestCase
    时如何调用
    getContext()
    ”。
  • 某个测试继承
    junit.framework.TestCase
    (JUnit3 风格:覆盖
    setUp()
    、采用
    testFoo()
    命名,并使用
    junit.framework.Assert
    的
    assertEquals
    ),而团队希望迁移到 JUnit4。
  • 用户提到
    MoreAsserts.assertContentsInAnyOrder
    /
    assertEquals(int[], int[])
    /
    assertContainsRegex
    、
    ViewAsserts.assertOnScreen
    、
    TouchUtils.tapView
    /
    dragQuarterScreenDown
    或
    android.test.suitebuilder.annotation.SmallTest
    。

When NOT to use this skill

何时不应使用此 skill

  • The codebase is already on AndroidX Test and the question is about using it (the runner,
    ActivityScenario
    , Espresso,
    ServiceTestRule
    ) — go straight to
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    ,
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    ,
    ../../../instrumentation/espresso/writing-espresso-tests/SKILL.md
    .
  • The question is about
    kotlin.test
    assertions (
    assertEquals
    ,
    assertFailsWith
    ) — use
    ../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.md
    . (
    kotlin.test
    is one valid target for
    MoreAsserts
    calls.)
  • The legacy class in question is a Robolectric shadow or a JUnit3 non-Android
    TestCase
    in pure-JVM code — for the JVM/Robolectric side use
    ../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
    and
    ../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md
    .
  • The user wants to write a new test — do not start from
    android.test.*
    at all; use the AndroidX skills directly.
  • 代码库已经使用 AndroidX Test,且问题是如何使用它(runner、
    ActivityScenario
    、Espresso、
    ServiceTestRule
    )——直接前往
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    、
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    、
    ../../../instrumentation/espresso/writing-espresso-tests/SKILL.md
    。
  • 问题涉及
    kotlin.test
    断言(
    assertEquals
    、
    assertFailsWith
    )——使用
    ../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.md
    。(
    kotlin.test
    是
    MoreAsserts
    调用的一个有效替代方案。)
  • 所涉及的旧版类是纯 JVM 代码中的 Robolectric shadow 或 JUnit3 非 Android
    TestCase
    ——对于 JVM/Robolectric 侧,使用
    ../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
    和
    ../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md
    。
  • 用户想编写新测试——不要从
    android.test.*
    开始;直接使用 AndroidX skills。

Prerequisites

前置条件

  • AndroidX Test on the test classpath — see
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    for the exact coordinate matrix (
    androidx.test:core
    ,
    :runner
    ,
    :rules
    ,
    androidx.test.ext:junit
    ). For host/JVM tests,
    ../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md
    .
  • JUnit4 on the classpath (
    junit:junit:4.13.2
    or via
    kotlin("test")
    ). The legacy classes are JUnit3-shaped (
    extends TestCase
    ); the migration target is JUnit4 (
    @Test
    +
    @RunWith
    ).
  • Espresso (
    androidx.test.espresso:espresso-core
    ) for anything that was using
    TouchUtils
    /
    ViewAsserts
    /
    ActivityInstrumentationTestCase2
    's UI poking.
  • 测试 classpath 上需有 AndroidX Test——参见
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    获取确切的依赖坐标矩阵(
    androidx.test:core
    、
    :runner
    、
    :rules
    、
    androidx.test.ext:junit
    )。对于主机/JVM 测试,请参阅
    ../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md
    。
  • 测试 classpath 上需有 JUnit4(
    junit:junit:4.13.2
    ,或通过
    kotlin("test")
    引入)。旧版类是 JUnit3 形态(
    extends TestCase
    );迁移目标是 JUnit4(
    @Test
    +
    @RunWith
    )。
  • 对于原先使用
    TouchUtils
    /
    ViewAsserts
    /
    ActivityInstrumentationTestCase2
    操作 UI 的逻辑,需使用 Espresso(
    androidx.test.espresso:espresso-core
    )。

The replacement map

替换映射

Legacy
android.test.*
(deprecated)
Use insteadNotes
InstrumentationTestRunner
(the
testInstrumentationRunner
)
androidx.test.runner.AndroidJUnitRunner
Change
android.defaultConfig.testInstrumentationRunner
. The legacy runner does not run JUnit4 or Espresso correctly.
InstrumentationTestCase
@RunWith(AndroidJUnit4::class)
+
InstrumentationRegistry.getInstrumentation()
getInstrumentation()
→
androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()
.
injectInstrumentation(...)
is gone.
sendKeys
/
runTestOnUiThread
→
getInstrumentation().runOnMainSync { … }
or
@UiThreadTest
.
AndroidTestCase
@RunWith(AndroidJUnit4::class)
+
ApplicationProvider.getApplicationContext()
getContext()
→
ApplicationProvider.getApplicationContext<Context>()
.
getTestContext()
(the test APK's context) →
InstrumentationRegistry.getInstrumentation().context
.
ApplicationTestCase<T>
@RunWith(AndroidJUnit4::class)
, drive
Application
via
ApplicationProvider.getApplicationContext()
No 1:1 base class — the
Application
is just a context now; assert on it directly.
ActivityInstrumentationTestCase2<T>
,
ActivityUnitTestCase<T>
,
SingleLaunchActivityTestCase<T>
ActivityScenario<T>
/
@get:Rule ActivityScenarioRule<T>
(+ Espresso for UI)
getActivity()
→
scenario.onActivity { activity -> … }
.
setActivityIntent(intent)
→
ActivityScenario.launch<T>(intent)
.
getInstrumentation().waitForIdleSync()
→ Espresso's automatic sync. See
../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
.
(Fragment cases, if any home-grown)
FragmentScenario
/
launchFragmentInContainer
../../../instrumentation/scenarios/launching-fragments-with-fragmentscenario/SKILL.md
.
ServiceTestCase<T>
androidx.test.rule.ServiceTestRule
startService(intent)
/
bindService(intent)
move onto the rule (
@get:Rule val serviceRule = ServiceTestRule()
);
getService()
→ the
IBinder
from
serviceRule.bindService(intent)
.
ProviderTestCase2<T>
androidx.test.rule.provider.ProviderTestRule
ProviderTestCase2
is the JUnit3-shaped form;
ProviderTestRule.Builder(MyProvider::class.java, AUTHORITY).build()
is the JUnit4 way and still gives an isolated
ContentResolver
.
LoaderTestCase
(Loaders are themselves deprecated)Migrate the Loader to a
ViewModel
+ coroutines/
Flow
first, then test that with
runTest
/ Turbine.
MoreAsserts
(
assertContentsInAnyOrder
,
assertEquals(int[], int[])
,
assertEmpty
,
assertNotEqual
,
assertContainsRegex
,
checkEqualsAndHashCodeMethods
)
Google Truth (
assertThat(list).containsExactly(...)
,
.isEmpty()
,
.containsMatch(regex)
), Hamcrest, or
kotlin.test.assertContentEquals
for ordered arrays
The platform Javadoc says "use Hamcrest"; Truth reads better.
androidx.test.ext:truth
ships Android-specific Truth subjects.
ViewAsserts
(
assertOnScreen
,
assertHorizontalCenterAligned
,
assertBottomAligned
, …)
Espresso
ViewMatchers
+
ViewAssertions
(
matches(isCompletelyDisplayed())
, layout-relation custom matchers)
See
../../../instrumentation/espresso/writing-espresso-tests/SKILL.md
.
TouchUtils
(
tapView
,
clickView
,
longClickView
,
dragQuarterScreenDown
,
scrollToBottom
,
dragViewToTop
)
Espresso
ViewActions
(
click()
,
longClick()
,
swipeUp()
/
swipeDown()
,
scrollTo()
,
GeneralSwipeAction
)
The legacy methods need a live
Instrumentation
+ Activity reference; Espresso actions run inside
onView(...).perform(...)
.
android.test.UiThreadTest
androidx.test.annotation.UiThreadTest
Just change the import; or replace with
getInstrumentation().runOnMainSync { … }
/
scenario.onActivity { … }
(which is already on the main thread).
android.test.FlakyTest
androidx.test.filters.FlakyTest
Import change.
android.test.suitebuilder.annotation.SmallTest
/
MediumTest
/
LargeTest
/
Suppress
androidx.test.filters.SmallTest
/
MediumTest
/
LargeTest
/
Suppress
Import change; the runner reads
-e size small
against the AndroidX annotations.
android.test.InstrumentationTestSuite
,
android.test.suitebuilder.TestSuiteBuilder
JUnit4
@RunWith(Suite::class)
+
@Suite.SuiteClasses([...])
, or just let
AndroidJUnitRunner
discover by
@SmallTest
/package
Manual suite building is rarely needed once the AndroidX runner is in place.
android.test.mock.MockContext
A real context (
ApplicationProvider.getApplicationContext()
), or Robolectric's context on the JVM, or
mock(Context::class.java)
(Mockito/MockK) for tight isolation
MockContext
throws
UnsupportedOperationException
from almost every method — it was a hand-stubbing base, which a mocking framework does better.
android.test.mock.MockContentResolver
+
MockContentProvider
ProviderTestRule
(isolated resolver), or a real
ContentResolver
from a Robolectric/instrumented context
If you genuinely need a stub resolver, Mockito a
ContentResolver
.
android.test.mock.MockPackageManager
Mockito/MockK
mock(PackageManager::class.java)
The platform Javadoc explicitly says "use a mocking framework like Mockito".
android.test.mock.MockResources
/
MockCursor
/
MockDialogInterface
/
MockApplication
/
MockService
Mockito/MockK mocks, or real instances from a test contextSame story — these were stub bases, mocking frameworks supersede them.
android.test.AndroidTestRunner
,
android.test.PerformanceTestCase
,
android.test.RepetitiveTest
AndroidJUnitRunner
;
androidx.benchmark
(Microbenchmark/Macrobenchmark); a custom JUnit4
@Rule
or just a loop
PerformanceTestCase
predates
androidx.benchmark
— real perf testing belongs there.
extends junit.framework.TestCase
+
assertEquals
from
junit.framework.Assert
(JUnit3 shape)
@RunWith(AndroidJUnit4::class)
+
@Test
methods +
org.junit.Assert.*
/
kotlin.test.*
Method names no longer need a
test
prefix;
setUp
/
tearDown
overrides become
@Before
/
@After
(or
@BeforeTest
/
@AfterTest
).
The platform's own
@deprecated
Javadoc often points at the old "Android Testing Support Library" /
android.support.test.*
names (e.g.
ActivityTestRule
). Those became
androidx.test.*
, and several have since been re-deprecated again —
ActivityTestRule
→
ActivityScenario
. Migrate to the current target in the table above, not to whatever the platform Javadoc literally says.
旧版
android.test.*
(已弃用)
改用说明
InstrumentationTestRunner
(
testInstrumentationRunner
)
androidx.test.runner.AndroidJUnitRunner
将
android.defaultConfig.testInstrumentationRunner
改为该值。旧版 runner 无法正确运行 JUnit4 或 Espresso。
InstrumentationTestCase
@RunWith(AndroidJUnit4::class)
+
InstrumentationRegistry.getInstrumentation()
getInstrumentation()
→
androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()
。
injectInstrumentation(...)
已移除。
sendKeys
/
runTestOnUiThread
→
getInstrumentation().runOnMainSync { … }
或
@UiThreadTest
。
AndroidTestCase
@RunWith(AndroidJUnit4::class)
+
ApplicationProvider.getApplicationContext()
getContext()
→
ApplicationProvider.getApplicationContext<Context>()
。
getTestContext()
(测试 APK 的上下文)→
InstrumentationRegistry.getInstrumentation().context
。
ApplicationTestCase<T>
@RunWith(AndroidJUnit4::class)
,通过
ApplicationProvider.getApplicationContext()
操作
Application
没有 1:1 的基类——现在
Application
只是一个 context,可直接对其断言。
ActivityInstrumentationTestCase2<T>
、
ActivityUnitTestCase<T>
、
SingleLaunchActivityTestCase<T>
ActivityScenario<T>
/
@get:Rule ActivityScenarioRule<T>
(UI 测试另加 Espresso)
getActivity()
→
scenario.onActivity { activity -> … }
。
setActivityIntent(intent)
→
ActivityScenario.launch<T>(intent)
。
getInstrumentation().waitForIdleSync()
→ Espresso 的自动同步。参见
../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
。
Fragment 测试用例(如果有自行实现的部分)
FragmentScenario
/
launchFragmentInContainer
../../../instrumentation/scenarios/launching-fragments-with-fragmentscenario/SKILL.md
。
ServiceTestCase<T>
androidx.test.rule.ServiceTestRule
startService(intent)
/
bindService(intent)
改由 rule 提供(
@get:Rule val serviceRule = ServiceTestRule()
);
getService()
→
serviceRule.bindService(intent)
返回的
IBinder
。
ProviderTestCase2<T>
androidx.test.rule.provider.ProviderTestRule
ProviderTestCase2
是 JUnit3 形态;
ProviderTestRule.Builder(MyProvider::class.java, AUTHORITY).build()
是 JUnit4 方式,仍可提供隔离的
ContentResolver
。
LoaderTestCase
(Loader 本身也已弃用)先将 Loader 迁移为
ViewModel
+ coroutine/
Flow
,然后使用
runTest
/ Turbine 进行测试。
MoreAsserts
(
assertContentsInAnyOrder
、
assertEquals(int[], int[])
、
assertEmpty
、
assertNotEqual
、
assertContainsRegex
、
checkEqualsAndHashCodeMethods
)
Google Truth(
assertThat(list).containsExactly(...)
、
.isEmpty()
、
.containsMatch(regex)
)、Hamcrest,或对有序数组使用
kotlin.test.assertContentEquals
平台 Javadoc 表示“使用 Hamcrest”;Truth 的可读性更好。
androidx.test.ext:truth
提供 Android 专用的 Truth subject。
ViewAsserts
(
assertOnScreen
、
assertHorizontalCenterAligned
、
assertBottomAligned
等)
Espresso
ViewMatchers
+
ViewAssertions
(
matches(isCompletelyDisplayed())
、布局关系自定义 matcher)
参见
../../../instrumentation/espresso/writing-espresso-tests/SKILL.md
。
TouchUtils
(
tapView
、
clickView
、
longClickView
、
dragQuarterScreenDown
、
scrollToBottom
、
dragViewToTop
)
Espresso
ViewActions
(
click()
、
longClick()
、
swipeUp()
/
swipeDown()
、
scrollTo()
、
GeneralSwipeAction
)
旧版方法需要有效的
Instrumentation
和 Activity 引用;Espresso 操作在
onView(...).perform(...)
内运行。
android.test.UiThreadTest
androidx.test.annotation.UiThreadTest
只需更改 import;或替换为
getInstrumentation().runOnMainSync { … }
/
scenario.onActivity { … }
(后者已位于主线程)。
android.test.FlakyTest
androidx.test.filters.FlakyTest
更改 import。
android.test.suitebuilder.annotation.SmallTest
/
MediumTest
/
LargeTest
/
Suppress
androidx.test.filters.SmallTest
/
MediumTest
/
LargeTest
/
Suppress
更改 import;runner 会针对 AndroidX 注解读取
-e size small
。
android.test.InstrumentationTestSuite
、
android.test.suitebuilder.TestSuiteBuilder
JUnit4
@RunWith(Suite::class)
+
@Suite.SuiteClasses([...])
,或者直接让
AndroidJUnitRunner
通过
@SmallTest
/package 发现
有了 AndroidX runner 后,通常不再需要手动构建测试套件。
android.test.mock.MockContext
真实 context(
ApplicationProvider.getApplicationContext()
)、JVM 上的 Robolectric context,或用于严格隔离的
mock(Context::class.java)
(Mockito/MockK)
MockContext
几乎所有方法都会抛出
UnsupportedOperationException
——它只是一个手工 stub 基类,而 mocking framework 更适合完成这项工作。
android.test.mock.MockContentResolver
+
MockContentProvider
ProviderTestRule
(隔离的 resolver),或来自 Robolectric/instrumentation context 的真实
ContentResolver
如果确实需要 stub resolver,请使用 Mockito mock
ContentResolver
。
android.test.mock.MockPackageManager
Mockito/MockK
mock(PackageManager::class.java)
平台 Javadoc 明确表示“使用 Mockito 等 mocking framework”。
android.test.mock.MockResources
/
MockCursor
/
MockDialogInterface
/
MockApplication
/
MockService
Mockito/MockK mock,或测试 context 中的真实实例同理——这些都是 stub 基类,现已被 mocking framework 取代。
android.test.AndroidTestRunner
、
android.test.PerformanceTestCase
、
android.test.RepetitiveTest
AndroidJUnitRunner
;
androidx.benchmark
(Microbenchmark/Macrobenchmark);自定义 JUnit4
@Rule
或直接使用循环
PerformanceTestCase
早于
androidx.benchmark
出现——真正的性能测试应放在
androidx.benchmark
中。
extends junit.framework.TestCase
+ 来自
junit.framework.Assert
的
assertEquals
(JUnit3 形态)
@RunWith(AndroidJUnit4::class)
+
@Test
方法 +
org.junit.Assert.*
/
kotlin.test.*
方法名不再需要
test
前缀;
setUp
/
tearDown
覆盖方法改为
@Before
/
@After
(或
@BeforeTest
/
@AfterTest
)。
平台自身的
@deprecated
Javadoc 经常指向旧的“Android Testing Support Library” /
android.support.test.*
名称(例如
ActivityTestRule
)。这些名称后来变成了
androidx.test.*
,其中若干项之后又被重新弃用——
ActivityTestRule
→
ActivityScenario
。请迁移到上表中的当前目标,不要照搬平台 Javadoc 字面所写的内容。

Workflow

工作流

  • 1. Flip the runner first. Set
    android.defaultConfig.testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    and add the AndroidX Test deps. Until this is done, JUnit4/Espresso/
    ActivityScenario
    cannot run. (
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    .)
  • 2. Convert one test class at a time, JUnit3 → JUnit4. Drop
    extends …TestCase
    , add
    @RunWith(AndroidJUnit4::class)
    , annotate test methods
    @Test
    , convert
    setUp()
    /
    tearDown()
    overrides to
    @Before
    /
    @After
    (no
    super
    call), and rename
    testFoo
    →
    foo
    if you like. Replace each legacy accessor with its AndroidX equivalent from the table.
  • 3. Replace base-class superpowers with explicit AndroidX entry points.
    getContext()
    →
    ApplicationProvider.getApplicationContext()
    ;
    getInstrumentation()
    →
    InstrumentationRegistry.getInstrumentation()
    ;
    getActivity()
    →
    ActivityScenario
    +
    onActivity { }
    ;
    getService()
    →
    ServiceTestRule.bindService(...)
    .
  • 4. Swap the assertion helpers.
    MoreAsserts.*
    → Truth/
    kotlin.test
    ;
    ViewAsserts.*
    → Espresso
    ViewAssertions
    ;
    TouchUtils.*
    → Espresso
    ViewActions
    .
  • 5. Swap the mock contexts. Anything extending
    android.test.mock.MockContext
    /
    MockResources
    /
    MockPackageManager
    → a real test context where possible, otherwise a Mockito/MockK mock. (
    ../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
    .)
  • 6. Delete the legacy imports and confirm nothing references
    android.test.*
    or
    android.test.mock.*
    any more.
    A clean module compiles with zero
    import android.test.
    lines.
  • 1. 首先切换 runner。 将
    android.defaultConfig.testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    并添加 AndroidX Test 依赖。在此完成之前,JUnit4/Espresso/
    ActivityScenario
    无法运行。(
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    。)
  • 2. 每次迁移一个测试类,从 JUnit3 → JUnit4。 移除
    extends …TestCase
    ,添加
    @RunWith(AndroidJUnit4::class)
    ,为测试方法添加
    @Test
    ,将
    setUp()
    /
    tearDown()
    覆盖方法转换为
    @Before
    /
    @After
    (无需调用
    super
    ),如果愿意,可以将
    testFoo
    重命名为
    foo
    。按照表格将每个旧版 accessor 替换为对应的 AndroidX 替代项。
  • 3. 用显式 AndroidX 入口替换基类自带的能力。
    getContext()
    →
    ApplicationProvider.getApplicationContext()
    ;
    getInstrumentation()
    →
    InstrumentationRegistry.getInstrumentation()
    ;
    getActivity()
    →
    ActivityScenario
    +
    onActivity { }
    ;
    getService()
    →
    ServiceTestRule.bindService(...)
    。
  • 4. 替换断言辅助方法。
    MoreAsserts.*
    → Truth/
    kotlin.test
    ;
    ViewAsserts.*
    → Espresso
    ViewAssertions
    ;
    TouchUtils.*
    → Espresso
    ViewActions
    。
  • 5. 替换 mock 上下文。 任何继承
    android.test.mock.MockContext
    /
    MockResources
    /
    MockPackageManager
    的类 → 尽可能使用真实测试上下文,否则使用 Mockito/MockK mock。(
    ../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
    。)
  • 6. 删除旧版 import,并确认不再引用
    android.test.*
    或
    android.test.mock.*
    。
    完成清理的模块应在不存在任何
    import android.test.
    行的情况下成功编译。

Patterns

模式

Pattern:
ActivityInstrumentationTestCase2
→
ActivityScenario

模式:
ActivityInstrumentationTestCase2
→
ActivityScenario

kotlin
// WRONG — deprecated base class
class LoginActivityTest : ActivityInstrumentationTestCase2<LoginActivity>(LoginActivity::class.java) {
    fun testTitleShown() {
        val activity = activity                       // getActivity()
        assertEquals("Sign in", activity.title)
    }
}
// WRONG because: android.test.ActivityInstrumentationTestCase2 is @Deprecated; it ties the test to
// the legacy InstrumentationTestRunner, blocks JUnit4/Espresso, and getActivity() leaks the Activity
// off the main thread.
kotlin
// RIGHT — ActivityScenario + JUnit4
@RunWith(AndroidJUnit4::class)
class LoginActivityTest {
    @get:Rule val scenario = ActivityScenarioRule(LoginActivity::class.java)

    @Test fun titleShown() {
        scenario.scenario.onActivity { activity ->
            assertEquals("Sign in", activity.title)
        }
        onView(withId(R.id.title)).check(matches(withText("Sign in")))   // or assert via Espresso
    }
}
kotlin
// WRONG — deprecated base class
class LoginActivityTest : ActivityInstrumentationTestCase2<LoginActivity>(LoginActivity::class.java) {
    fun testTitleShown() {
        val activity = activity                       // getActivity()
        assertEquals("Sign in", activity.title)
    }
}
// WRONG because: android.test.ActivityInstrumentationTestCase2 is @Deprecated; it ties the test to
// the legacy InstrumentationTestRunner, blocks JUnit4/Espresso, and getActivity() leaks the Activity
// off the main thread.
kotlin
// RIGHT — ActivityScenario + JUnit4
@RunWith(AndroidJUnit4::class)
class LoginActivityTest {
    @get:Rule val scenario = ActivityScenarioRule(LoginActivity::class.java)

    @Test fun titleShown() {
        scenario.scenario.onActivity { activity ->
            assertEquals("Sign in", activity.title)
        }
        onView(withId(R.id.title)).check(matches(withText("Sign in")))   // or assert via Espresso
    }
}

Pattern:
AndroidTestCase
→
@RunWith(AndroidJUnit4)
+
ApplicationProvider

模式:
AndroidTestCase
→
@RunWith(AndroidJUnit4)
+
ApplicationProvider

kotlin
// WRONG
class FormatterTest : AndroidTestCase() {
    fun testCurrency() {
        val s = CurrencyFormatter(context).format(1099)   // getContext()
        assertEquals("$10.99", s)
    }
}
// WRONG because: android.test.AndroidTestCase is @Deprecated; getContext() and the TestCase shape
// are the legacy world.
kotlin
// RIGHT
@RunWith(AndroidJUnit4::class)
class FormatterTest {
    private val context: Context = ApplicationProvider.getApplicationContext()

    @Test fun currency() {
        assertEquals("$10.99", CurrencyFormatter(context).format(1099))
    }
}
kotlin
// WRONG
class FormatterTest : AndroidTestCase() {
    fun testCurrency() {
        val s = CurrencyFormatter(context).format(1099)   // getContext()
        assertEquals("$10.99", s)
    }
}
// WRONG because: android.test.AndroidTestCase is @Deprecated; getContext() and the TestCase shape
// are the legacy world.
kotlin
// RIGHT
@RunWith(AndroidJUnit4::class)
class FormatterTest {
    private val context: Context = ApplicationProvider.getApplicationContext()

    @Test fun currency() {
        assertEquals("$10.99", CurrencyFormatter(context).format(1099))
    }
}

Pattern:
MoreAsserts
/
TouchUtils
calls

模式:
MoreAsserts
/
TouchUtils
调用

kotlin
// WRONG
MoreAsserts.assertContentsInAnyOrder(ids, 3L, 1L, 2L)         // android.test.MoreAsserts (deprecated)
TouchUtils.tapView(this, listView)                            // android.test.TouchUtils (deprecated)
ViewAsserts.assertOnScreen(rootView, listView)                // android.test.ViewAsserts (deprecated)
kotlin
// RIGHT
assertThat(service.ids()).containsExactly(1L, 2L, 3L)         // Google Truth (order-insensitive)
onView(withId(R.id.list)).perform(click())                    // Espresso ViewActions
onView(withId(R.id.list)).check(matches(isCompletelyDisplayed()))   // Espresso ViewAssertions
kotlin
// WRONG
MoreAsserts.assertContentsInAnyOrder(ids, 3L, 1L, 2L)         // android.test.MoreAsserts (deprecated)
TouchUtils.tapView(this, listView)                            // android.test.TouchUtils (deprecated)
ViewAsserts.assertOnScreen(rootView, listView)                // android.test.ViewAsserts (deprecated)
kotlin
// RIGHT
assertThat(service.ids()).containsExactly(1L, 2L, 3L)         // Google Truth (order-insensitive)
onView(withId(R.id.list)).perform(click())                    // Espresso ViewActions
onView(withId(R.id.list)).check(matches(isCompletelyDisplayed()))   // Espresso ViewAssertions

Pattern:
android.test.mock.MockContext
subclass → real context or Mockito

模式:
android.test.mock.MockContext
子类 → 真实 context 或 Mockito

kotlin
// WRONG
class FakeContext : MockContext() {                            // android.test.mock.MockContext (deprecated)
    override fun getPackageName() = "com.example"
    // every other method throws UnsupportedOperationException
}
kotlin
// RIGHT — a real test context if the SUT just reads from it
val context: Context = ApplicationProvider.getApplicationContext()

// RIGHT — a mock if you must control specific calls in isolation
val context = mock<Context> { on { packageName } doReturn "com.example" }
kotlin
// WRONG
class FakeContext : MockContext() {                            // android.test.mock.MockContext (deprecated)
    override fun getPackageName() = "com.example"
    // every other method throws UnsupportedOperationException
}
kotlin
// RIGHT — a real test context if the SUT just reads from it
val context: Context = ApplicationProvider.getApplicationContext()

// RIGHT — a mock if you must control specific calls in isolation
val context = mock<Context> { on { packageName } doReturn "com.example" }

Mandatory rules

强制规则

  • MUST NOT add new tests using any
    android.test.*
    or
    android.test.mock.*
    class — all are
    @Deprecated
    . New tests use AndroidX Test (
    AndroidJUnit4
    ,
    ActivityScenario
    ,
    ServiceTestRule
    ,
    ProviderTestRule
    , Espresso) and
    org.junit
    /
    kotlin.test
    assertions.
  • MUST switch
    testInstrumentationRunner
    to
    androidx.test.runner.AndroidJUnitRunner
    before (or as the first step of) migrating any test class — the legacy
    InstrumentationTestRunner
    does not run JUnit4/Espresso.
  • MUST replace
    getActivity()
    /
    setActivityIntent()
    with
    ActivityScenario
    (
    launch
    ,
    onActivity { }
    ), not with
    ActivityTestRule
    —
    ActivityTestRule
    is itself deprecated.
  • MUST replace
    android.test.mock.MockContext
    /
    MockResources
    /
    MockPackageManager
    /
    MockContentResolver
    subclasses with a real test context where the SUT only reads from it, otherwise a Mockito/MockK mock — never re-derive a new hand-stub from
    MockContext
    .
  • MUST convert JUnit3 shape (
    extends TestCase
    ,
    testFoo()
    ,
    setUp()
    /
    tearDown()
    overrides,
    junit.framework.Assert
    ) to JUnit4 (
    @RunWith(AndroidJUnit4)
    ,
    @Test
    ,
    @Before
    /
    @After
    ,
    org.junit.Assert
    /
    kotlin.test
    ) — do not leave a class half-migrated.
  • MUST NOT trust the platform
    @deprecated
    Javadoc's literal target (it often names the obsolete
    android.support.test.*
    API); migrate to the current AndroidX target in this skill's table.
  • PREFERRED: migrate one test class fully per change, with the runner flip landing first; a half-migrated module (some classes on
    android.test.*
    , some on AndroidX) is hard to reason about.
  • PREFERRED: Google Truth (
    androidx.test.ext:truth
    for the Android subjects) over Hamcrest as the
    MoreAsserts
    replacement — better failure messages.
  • 不得(MUST NOT):添加任何使用
    android.test.*
    或
    android.test.mock.*
    类的新测试——它们全部已标记为
    @Deprecated
    。新测试应使用 AndroidX Test(
    AndroidJUnit4
    、
    ActivityScenario
    、
    ServiceTestRule
    、
    ProviderTestRule
    、Espresso)以及
    org.junit
    /
    kotlin.test
    断言。
  • 必须(MUST):在迁移任何测试类之前(或作为迁移的第一步)将
    testInstrumentationRunner
    切换到
    androidx.test.runner.AndroidJUnitRunner
    ——旧版
    InstrumentationTestRunner
    无法运行 JUnit4/Espresso。
  • 必须(MUST):将
    getActivity()
    /
    setActivityIntent()
    替换为
    ActivityScenario
    (
    launch
    、
    onActivity { }
    ),而不是
    ActivityTestRule
    ——
    ActivityTestRule
    本身也已弃用。
  • 必须(MUST):当 SUT 仅读取上下文时,将
    android.test.mock.MockContext
    /
    MockResources
    /
    MockPackageManager
    /
    MockContentResolver
    子类替换为真实测试上下文;否则使用 Mockito/MockK mock——绝不能基于
    MockContext
    重新实现新的手工 stub。
  • 必须(MUST):将 JUnit3 形态(
    extends TestCase
    、
    testFoo()
    、
    setUp()
    /
    tearDown()
    覆盖方法、
    junit.framework.Assert
    )完整转换为 JUnit4(
    @RunWith(AndroidJUnit4)
    、
    @Test
    、
    @Before
    /
    @After
    、
    org.junit.Assert
    /
    kotlin.test
    )——不能让测试类处于半迁移状态。
  • 不得(MUST NOT):直接信任平台
    @deprecated
    Javadoc 给出的字面目标(它通常指向已经过时的
    android.support.test.*
    API);应迁移到本 skill 表格中的当前 AndroidX 目标。
  • 优先(PREFERRED):每次变更完整迁移一个测试类,并首先完成 runner 切换;半迁移模块(部分类仍使用
    android.test.*
    ,部分类已使用 AndroidX)很难理解和维护。
  • 优先(PREFERRED):使用 Google Truth(Android subject 使用
    androidx.test.ext:truth
    )替代 Hamcrest 作为
    MoreAsserts
    的替代方案——它的失败消息更清晰。

Verification

验证

  • git grep -n 'import android.test\.' -- '*.java' '*.kt'
    is empty (or limited to a tracked, justified holdout list).
  • No module's
    testInstrumentationRunner
    is
    android.test.InstrumentationTestRunner
    ; all are
    androidx.test.runner.AndroidJUnitRunner
    .
  • No test class
    extends ActivityInstrumentationTestCase2
    /
    AndroidTestCase
    /
    InstrumentationTestCase
    /
    ServiceTestCase
    /
    ProviderTestCase2
    /
    junit.framework.TestCase
    .
  • No
    MoreAsserts.
    /
    ViewAsserts.
    /
    TouchUtils.
    references remain.
  • No subclass of
    android.test.mock.MockContext
    /
    MockResources
    /
    MockPackageManager
    /
    MockContentResolver
    remains.
  • Migrated instrumentation tests run green under
    ./gradlew :module:connectedDebugAndroidTest
    ; migrated host tests under
    ./gradlew :module:testDebugUnitTest
    .
  • git grep -n 'import android.test\.' -- '*.java' '*.kt'
    的输出为空(或仅剩已登记且有合理理由的暂缓项列表)。
  • 没有模块的
    testInstrumentationRunner
    是
    android.test.InstrumentationTestRunner
    ;所有模块均使用
    androidx.test.runner.AndroidJUnitRunner
    。
  • 没有测试类
    extends ActivityInstrumentationTestCase2
    /
    AndroidTestCase
    /
    InstrumentationTestCase
    /
    ServiceTestCase
    /
    ProviderTestCase2
    /
    junit.framework.TestCase
    。
  • 不再存在
    MoreAsserts.
    /
    ViewAsserts.
    /
    TouchUtils.
    引用。
  • 不再存在
    android.test.mock.MockContext
    /
    MockResources
    /
    MockPackageManager
    /
    MockContentResolver
    的子类。
  • 迁移后的 instrumentation 测试可通过
    ./gradlew :module:connectedDebugAndroidTest
    成功运行;迁移后的主机测试可通过
    ./gradlew :module:testDebugUnitTest
    成功运行。

References

参考资料

  • developer.android.com/training/testing — AndroidX Test overview; the migration destination for everything in
    android.test.*
    .
  • developer.android.com/reference/android/test/package-summary — the
    android.test
    package reference, every class marked deprecated with its replacement pointer.
  • frameworks/base/test-base/src/android/test/AndroidTestCase.java
    ,
    InstrumentationTestCase.java
    ,
    UiThreadTest.java
    ,
    FlakyTest.java
    (AOSP) —
    @Deprecated
    classes whose Javadoc routes to
    InstrumentationRegistry
    /
    androidx.test.annotation.UiThreadTest
    /
    androidx.test.filters.FlakyTest
    .
  • frameworks/base/test-runner/src/android/test/ActivityInstrumentationTestCase2.java
    ,
    ServiceTestCase.java
    ,
    ProviderTestCase2.java
    ,
    InstrumentationTestRunner.java
    ,
    MoreAsserts.java
    ,
    ViewAsserts.java
    ,
    TouchUtils.java
    (AOSP) — the deprecated runner/base classes; Javadocs name
    ActivityTestRule
    /
    ServiceTestRule
    /
    AndroidJUnitRunner
    /Hamcrest/Espresso as replacements.
  • frameworks/base/test-mock/src/android/test/mock/MockContext.java
    ,
    MockPackageManager.java
    ,
    MockContentResolver.java
    ,
    MockResources.java
    ,
    MockCursor.java
    (AOSP) — the stub-context bases;
    MockPackageManager
    's Javadoc explicitly says "use a mocking framework like Mockito".
  • Cross-set:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    — the
    AndroidJUnitRunner
    / AndroidX Test coordinate matrix to land first.
  • Cross-set:
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    —
    ActivityScenario
    /
    ActivityScenarioRule
    , the replacement for
    ActivityInstrumentationTestCase2
    .
  • Cross-set:
    ../../../instrumentation/scenarios/launching-fragments-with-fragmentscenario/SKILL.md
    —
    FragmentScenario
    for any home-grown fragment-test bases.
  • Cross-set:
    ../../../instrumentation/espresso/writing-espresso-tests/SKILL.md
    — Espresso
    ViewMatchers
    /
    ViewActions
    /
    ViewAssertions
    , the replacement for
    ViewAsserts
    /
    TouchUtils
    .
  • Cross-set:
    ../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
    — mocking
    Context
    /
    PackageManager
    /
    Resources
    , the replacement for
    android.test.mock.*
    .
  • Cross-set:
    ../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
    — real Android stubs on the JVM, an alternative to a mock context.
  • Cross-set:
    ../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.md
    —
    kotlin.test
    assertions (
    assertEquals
    ,
    assertContentEquals
    ,
    assertFailsWith
    ), one valid replacement for
    MoreAsserts
    and
    junit.framework.Assert
    .
  • Cross-set:
    ../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md
    —
    src/test/
    vs
    src/androidTest/
    , which the migrated classes need to be sorted into.
  • developer.android.com/training/testing — AndroidX Test 概览;所有
    android.test.*
    内容的迁移目标。
  • developer.android.com/reference/android/test/package-summary —
    android.test
    包参考,其中每个类都标记为已弃用并指向替代项。
  • frameworks/base/test-base/src/android/test/AndroidTestCase.java
    、
    InstrumentationTestCase.java
    、
    UiThreadTest.java
    、
    FlakyTest.java
    (AOSP)— 标记为
    @Deprecated
    的类,其 Javadoc 指向
    InstrumentationRegistry
    /
    androidx.test.annotation.UiThreadTest
    /
    androidx.test.filters.FlakyTest
    。
  • frameworks/base/test-runner/src/android/test/ActivityInstrumentationTestCase2.java
    、
    ServiceTestCase.java
    、
    ProviderTestCase2.java
    、
    InstrumentationTestRunner.java
    、
    MoreAsserts.java
    、
    ViewAsserts.java
    、
    TouchUtils.java
    (AOSP)— 已弃用的 runner/基类;其 Javadoc 将
    ActivityTestRule
    /
    ServiceTestRule
    /
    AndroidJUnitRunner
    /Hamcrest/Espresso 指定为替代项。
  • frameworks/base/test-mock/src/android/test/mock/MockContext.java
    、
    MockPackageManager.java
    、
    MockContentResolver.java
    、
    MockResources.java
    、
    MockCursor.java
    (AOSP)— stub context 基类;
    MockPackageManager
    的 Javadoc 明确表示“使用 Mockito 等 mocking framework”。
  • 跨技能集:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    — 需要优先落地的
    AndroidJUnitRunner
    / AndroidX Test 依赖坐标矩阵。
  • 跨技能集:
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    —
    ActivityScenario
    /
    ActivityScenarioRule
    ,用于替换
    ActivityInstrumentationTestCase2
    。
  • 跨技能集:
    ../../../instrumentation/scenarios/launching-fragments-with-fragmentscenario/SKILL.md
    —
    FragmentScenario
    ,用于替换自行实现的 fragment 测试基类。
  • 跨技能集:
    ../../../instrumentation/espresso/writing-espresso-tests/SKILL.md
    — Espresso
    ViewMatchers
    /
    ViewActions
    /
    ViewAssertions
    ,用于替换
    ViewAsserts
    /
    TouchUtils
    。
  • 跨技能集:
    ../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md
    — 使用 mocking framework 替换
    android.test.mock.*
    。
  • 跨技能集:
    ../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md
    — JVM 上的真实 Android stub,是 mock context 的替代方案。
  • 跨技能集:
    ../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.md
    —
    kotlin.test
    断言(
    assertEquals
    、
    assertContentEquals
    、
    assertFailsWith
    ),是
    MoreAsserts
    和
    junit.framework.Assert
    的有效替代方案。
  • 跨技能集:
    ../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md
    —
    src/test/
    与
    src/androidTest/
    的区别,以及迁移后的测试类应如何分类。