Instrumentation → Compose Testing

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 老项目迁移系列,持续更新中。

相关推荐
RobinXYuan26 分钟前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
炸薯条!27 分钟前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
SimonKing1 小时前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员
CoderYanger2 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis
Rain的Java大神之路2 小时前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
蜡笔小谢12 小时前
DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill
java·笔记·ai·agent·deepseek·harness
唐老板14 小时前
Spring AI 2.0 只支持 Boot 4
java
StarsGreen15 小时前
Android中的seccomp相关信息介绍
android
琳少_17 小时前
java程序设计笔记
java·开发语言·数据库·笔记
小荷才露尖尖角,早有蜻蜓立上头18 小时前
SpringBoot 定时任务
java·spring boot·后端