You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Espresso测试点击按钮后未跳转至目标Fragment是什么原因

导航跳转未触发的常见原因及修复方案

核心错误原因

  • 断言逻辑写错:你的测试代码中assertEquals判断的是action的ID,不是跳转后目标Fragment的ID。R.id.action_welcomeFragment_to_doctorRegistrationFragment是导航动作的唯一标识,跳转完成后currentDestination.id应该对应目标Fragment的ID:R.id.doctorRegistrationFragment,所以这行断言本身就是错的,哪怕跳转成功也会报失败。
  • TestNavHostController未配置起始目的地:调用setGraph之后没有显式指定当前所在的起始目的地为WelcomeFragment,导航控制器找不到对应起始页下的跳转action,自然不会执行跳转逻辑。
  • 目标Fragment布局XML语法错误:你提供的fragment_doctor_registration.xml存在标签不匹配问题:代码里只有</androidx.core.widget.NestedScrollView>结束标签,没有对应的开始标签,会导致目标Fragment inflate布局时崩溃,就算跳转触发也会失败。
  • 点击逻辑存在异步前置判断:如果WelcomeFragment里按钮点击事件执行导航前有异步操作(比如接口请求、权限校验等),Espresso默认不会等待异步任务执行完成,直接断言就会拿到跳转前的目的地。

修复后的测试代码

@Test
fun clickApplyAsADoctor(){
    val navController = TestNavHostController(
        ApplicationProvider.getApplicationContext())

    scenario.onFragment { fragment ->
        navController.setGraph(R.navigation.auth_navigation)
        // 显式设置当前起始目的地为WelcomeFragment
        navController.setCurrentDestination(R.id.welcomeFragment)
        Navigation.setViewNavController(fragment.requireView(), navController)
    }
    onView(withId(R.id.buttonDoctor)).perform(click())
    // 断言当前目的地是目标Fragment的ID,不是action的ID
    Assert.assertEquals(navController.currentDestination?.id, R.id.doctorRegistrationFragment)
}

额外排查点

  • 先修复目标Fragment的XML布局错误,补全NestedScrollView的开始标签或者删除多余的结束标签,保证目标Fragment可以正常创建。
  • 如果点击逻辑里存在异步操作,需要引入IdlingResource让Espresso等待异步任务执行完成后再执行断言。
  • 确认WelcomeFragment里buttonDoctor的点击事件确实调用了findNavController().navigate(R.id.action_welcomeFragment_to_doctorRegistrationFragment)执行导航。

内容的提问来源于stack exchange,提问作者Ahmet Yilmaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:45:04