Android instrumentation tests在API29抛出SecurityException异常
问题背景
- 基于JUnit、Espresso开发插桩测试(instrumented tests),实现Activity与Fragment测试流程自动化,测试套件计划部署到Firebase Test Lab运行,目前在搭载API 31的Pixel 6、API 30的Pixel 3设备上运行均正常。
- 同一套测试在搭载API 29的Pixel 2设备上运行时,首个测试启动Activity阶段触发崩溃,调试确认崩溃触发点为Activity
onCreate方法首行的super.onCreate(savedInstanceState)代码,相同设备、相同系统版本下普通模式启动应用无任何异常。 - 崩溃抛出的完整日志如下:
W/Binder: Caught a RuntimeException from the binder stub implementation. java.lang.SecurityException: Calling from not trusted UID! at android.app.UiAutomationConnection.throwIfCalledByNotTrustedUidLocked(UiAutomationConnection.java:520) at android.app.UiAutomationConnection.shutdown(UiAutomationConnection.java:424) at android.app.IUiAutomationConnection$Stub.onTransact(IUiAutomationConnection.java:390) at android.os.Binder.execTransactInternal(Binder.java:1021) at android.os.Binder.execTransact(Binder.java:994) Outgoing transactions from this process must be FLAG_ONEWAY java.lang.Throwable at android.os.BinderProxy.transact(BinderProxy.java:480) at android.app.IInstrumentationWatcher$Stub$Proxy.instrumentationFinished(IInstrumentationWatcher.java:205) at com.android.server.am.InstrumentationReporter$MyThread.run(InstrumentationReporter.java:86)
- 待确认问题:是否有开发者遇到过同类问题,该崩溃是否由Activity配置遗漏导致。
解决方案
该问题和Activity本身的配置、业务代码无关,是API 29(Android 10)系统侧UiAutomation服务校验逻辑、搭配旧版AndroidX Test依赖触发的已知兼容问题,按以下顺序排查修复即可:
- 统一升级测试依赖版本:将
androidx.test:core、androidx.test:runner、androidx.test:rules、androidx.test.espresso:espresso-core所有AndroidX Test相关依赖升级到1.4.0及以上稳定版。1.4.0之前的测试框架版本存在UiAutomation连接意外提前释放的缺陷,在API 29设备上触发系统侧非可信UID调用校验,直接抛出SecurityException。 - 检查测试包的Manifest配置:确认插桩测试对应的AndroidManifest.xml中没有配置
android:sharedUserId属性,如果测试包配置了和被测目标应用不一致的sharedUserId,会导致测试进程UID不被UiAutomation服务信任,直接触发该异常,移除测试包下的sharedUserId配置即可。 - 检查测试代码中的UiAutomation调用:如果在测试用例初始化阶段手动调用了
Instrumentation.getUiAutomation().shutdown()或跨进程UiAutomation相关操作,会提前断开系统持有的测试连接,后续启动Activity时系统尝试回收已断开的连接就会触发校验失败。不要手动干预测试框架对UiAutomation连接的生命周期管理,框架自动创建和销毁的连接不会触发该问题。 - 该异常仅在API 29系统上存在,API 30及以上版本谷歌已经修复了系统侧的UID校验逻辑缺陷,修复完成后即可在Firebase Test Lab全设备正常运行,未修复前可暂时跳过API 29的Pixel 2设备执行测试。
内容的提问来源于stack exchange,提问作者Daniel Schröder
相关产品推荐
相关产品推荐

