Instrumentation 测试(老写法)→ Compose Testing
老写法(Java --- Espresso Instrumentation)
java
@Test
public void clickButton_showsResult() {
onView(withId(R.id.btn_search)).perform(click());
onView(withId(R.id.tv_result)).check(matches(withText("结果")));
}
问题在哪里
Espresso 测试需要运行在设备/模拟器上,慢(每次至少几十秒)。ViewMatcher 的 withId + withText 嵌套查询对于复杂 UI 可读性很差。测试执行依赖 View 层级,UI 的任何改动都会影响测试。
新写法(Compose Testing)
kotlin
@Test
fun `click button shows result`() = runTest {
composeTestRule.setContent {
MyScreen(viewModel = fakeViewModel)
}
composeTestRule
.onNodeWithTag("btn_search")
.performClick()
composeTestRule
.onNodeWithTag("tv_result")
.assertTextEquals("结果")
}
一句话注意
Compose Testing 不依赖真实设备 View 层级,可以直接运行在 JVM 上(不需要模拟器),一秒内就能跑完。SemanticsNode 替代了 View,通过 testTag 定位元素比 Espresso 的 withId 更快更稳定。
如果项目是 View 和 Compose 混用,可以两者一起用------Compose 部分用 composeTestRule,View 部分用 Espresso。但新写的 Compose 页面直接用 Compose Testing 测试即可,不需要 Espresso。
Java Android 老项目迁移系列,持续更新中。