执行Android仪器化测试报错:找不到AndroidJUnitRunner的Instrumentation信息
看到你运行仪器化测试时遇到了Unable to find instrumentation info的错误,这个问题大多是因为测试APK的配置或者安装环节出了问题,我给你梳理几个排查和解决的步骤:
1. 检查Module级build.gradle的测试运行器配置
首先确认你的项目是否正确指定了测试运行器。打开你App模块的build.gradle文件,找到defaultConfig块,确保存在正确的testInstrumentationRunner配置:
android { defaultConfig { // 如果你用的是旧的Support Library,保留这行 testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" // 如果你已经迁移到AndroidX,必须改成AndroidX版本的runner // testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } }
如果是AndroidX项目,还要确保你的测试依赖是AndroidX版本的:
dependencies { androidTestImplementation 'androidx.test:runner:1.5.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' }
2. 确保测试APK正确安装到设备
有时候旧的测试APK残留会导致识别问题,先卸载旧的主APK和测试APK:
./adb -s emulator-5554 uninstall murali.myapplication ./adb -s emulator-5554 uninstall murali.myapplication.test
然后重新构建并安装APK,用Gradle命令会更省心:
./gradlew installDebug installDebugAndroidTest
如果手动安装的话,找到构建生成的APK文件路径执行:
./adb -s emulator-5554 install app/build/outputs/apk/debug/app-debug.apk ./adb -s emulator-5554 install app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
3. 验证设备上的Instrumentation组件是否存在
执行下面的命令,查看设备上已注册的instrumentation组件:
./adb -s emulator-5554 shell pm list instrumentation
你需要找到类似这样的条目:
instrumentation:murali.myapplication.test/android.support.test.runner.AndroidJUnitRunner (target=murali.myapplication)
如果找不到这个条目,说明测试APK没安装成功,或者配置的runner类名/包名有误。
4. 修正测试命令中的runner路径
如果你的项目是AndroidX,却在命令里用了旧的android.support.test.runner.AndroidJUnitRunner,肯定会找不到组件,此时要把命令里的runner改成AndroidX版本:
./adb -s emulator-5554 shell am instrument -w -r -e class murali.myapplication.Main3ActivityTest#addNewEmployee murali.myapplication.test/androidx.test.runner.AndroidJUnitRunner
按上面的步骤逐一排查,应该就能解决这个找不到instrumentation的问题了。
内容的提问来源于stack exchange,提问作者M.A.Murali

