位置:首页 > Kotlin > Instrumentation与Compose Testing实战指南

Instrumentation与Compose Testing实战指南

时间:2026-08-14  |  作者:风起客  |  阅读:0

Instrumentation 测试(老写法)→ Compose Testing

老写法(Ja va — Espresso Instrumentation)

@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 的任何改动都会影响测试。

Instrumentation→ComposeTesting

新写法(Compose Testing)

@Test
fun `click button shows result`() = runTest {
composeTestRule.setContent {
MyScreen(viewModel = fakeViewModel)
}

composeTestRule
.onNodeWithTag("btn_search")
.performClick()

composeTestRule
.onNodeWithTag("tv_result")
.assertTextEquals("结果")
}

Compose Testing 的优势

Compose Testing 不必依赖真实设备上的 View 层级。直接就在 JVM 上运行即可,连模拟器都不需要。

通常一秒内就能完成。

SemanticsNode 取代了 View,并且通过 testTag 来定位元素。

相比 Espresso 的 withId,这种方式往往更快,也更稳定。

混合项目怎么用

如果项目里同时混用了 View 和 Compose,那就两套工具配合着来。

  • Compose 部分交给 composeTestRule
  • View 部分继续用 Espresso
  • 新写的 Compose 页面,直接上 Compose Testing 就够了,没必要再绕回 Espresso

Ja va Android 老项目迁移系列,持续更新中。

免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多