Instrumentation与Compose Testing实战指南
时间:2026-08-14 | 作者:风起客 | 阅读:0Instrumentation 测试(老写法)→ 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 的任何改动都会影响测试。
新写法(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 老项目迁移系列,持续更新中。
免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。
相关文章
更多-
- 迅捷路由器怎么调信号最强,设置时要注意什么?
- 时间:2026-08-27
-
- vivo浏览器怎么卸不掉?原因和解决方法在这里
- 时间:2026-08-27
-
- OPPO R11s黑屏了,怎么强制恢复出厂设置?
- 时间:2026-08-27
-
- 飞利浦显示器包装盒有生产日期和保修期吗?怎么看?
- 时间:2026-08-27
-
- 联想新平板开机必须联网吗?怎么做?
- 时间:2026-08-27
-
- 平板横竖屏切换设置与问题解决
- 时间:2026-08-27
-
- 移动电源容量怎么测?要准备哪些工具?
- 时间:2026-08-27
-
- 荣耀90 Pro防水吗?防水级别多少?怎么用才安全
- 时间:2026-08-27
精选合集
更多大家都在玩
大家都在看
更多-
- 糖尿病完全不能吃糖吗
- 时间:2026-09-15
-
- 蚂蚁庄园小课堂2026年9月16日最新题目答案
- 时间:2026-09-15
-
- 小鸡答题今天的答案是什么2026年9月16日
- 时间:2026-09-15
-
- 蚂蚁庄园每日答题答案2026年9月16日
- 时间:2026-09-15
-
- 以下哪种粮食是酿造绍兴黄酒的主要原料 蚂蚁庄园今日答案9月16日
- 时间:2026-09-15
-
- 劝学名句“及时当勉励,岁月不待人”出自哪位诗人 蚂蚁庄园今日答案9.16
- 时间:2026-09-15
-
- 蚂蚁庄园今天答题答案2026年9月16日
- 时间:2026-09-15
-
- 蚂蚁庄园答题今日答案2026年9月16日
- 时间:2026-09-15
