Android Fragment测试挂起后失败,检测到0个测试执行求助
问题排查:Android Instrumented测试显示0个测试执行
问题描述
编写了如下Fragment测试代码:
@RunWith(AndroidJUnit4::class) class LogoutFragmentTest { @Test fun testEventFragment() { val scenario = launchFragment<LogoutFragment>( initialState = Lifecycle.State.INITIALIZED ) scenario.onFragment { fragment -> assertThat(fragment.m_Context).isNotNull() } } }
从androidTest文件夹右键执行“Run All tests”,模拟器启动并连接进程后,connectedDebugAndroidTests任务长时间挂起,最终测试结果显示:
INSTRUMENTATION_RESULT: stream= Test results for InstrumentationTestRunner= Time: 0.0 OK (0 tests) INSTRUMENTATION_CODE: -1
排查步骤
1. 检查测试类和方法的可见性
确保测试类LogoutFragmentTest和testEventFragment方法为public。Kotlin默认类和方法是public,若手动添加private修饰符会导致测试框架无法识别。
2. 验证依赖配置
确认build.gradle(Module)中已正确添加Instrumented测试依赖:
android { defaultConfig { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } } dependencies { // 核心测试依赖 androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' // Fragment测试依赖 androidTestImplementation 'androidx.fragment:fragment-testing:1.6.1' }
注意fragment-testing版本要与项目中fragment依赖版本匹配,避免版本冲突。
3. 检查测试类注解
确认@RunWith(AndroidJUnit4::class)注解正确,基础测试场景无需额外替换其他注解。
4. 清理重建项目
依次执行:
Build > Clean ProjectBuild > Rebuild Project- 重启Android Studio并重新连接模拟器
5. 检查设备/模拟器状态
- 使用最新系统镜像的模拟器,避免兼容性问题
- 关闭其他占用设备的进程(如其他测试任务、adb连接)
- 执行
adb kill-server后再adb start-server重启adb服务
6. 单独运行单个测试
右键点击testEventFragment方法单独执行,若能正常运行,说明批量测试存在配置干扰,检查androidTest文件夹下是否有其他错误测试类。
7. 确认测试类路径
确保LogoutFragmentTest位于androidTest/java/[应用包名]路径下,包名需与主代码包名一致,否则测试框架无法扫描到测试类。
8. 查看Gradle详细日志
执行命令./gradlew connectedDebugAndroidTests --info,通过详细日志定位任务挂起或测试未执行的具体原因(如依赖冲突、设备连接问题、测试类扫描失败等)。
内容的提问来源于stack exchange,提问作者Cristi
相关产品推荐
相关产品推荐

