Android Espresso使用onDevice().setScreenOrientation旋转模拟器失败(网络/代理/GRPC相关问题)
最近在做Espresso UI测试时,想调用API把模拟器从竖屏切换到横屏,按照官方文档的步骤完整配置后却踩了坑:不管是用规则还是直接调用onDevice().setScreenOrientation(ScreenOrientation.LANDSCAPE),都触发了连接错误,而且本地和CI环境的报错还不一样。
遇到的具体错误
本地工作管控机器上的错误
直接抛出核心异常:androidx.test.espresso.device.controller.DeviceControllerOperationException: Failed to set screen orientation. Please make sure the Android Emulator version is updated to 33.1.11+ and the controller gRPC service is enabled on the emulator.
底层堆栈追踪指向网络连接失败:
java.net.ConnectException: failed to connect to /10.0.2.2 (port 8554) from /:: (port 0): connect failed: ENETUNREACH (Network is unreachable)管控CI环境中的错误
报错更直接,聚焦在gRPC端口连接:androidx.test.espresso.device.controller.DeviceControllerOperationException: Unable to connect to Emulator gRPC port. Please make sure the Android Emulator version is updated to 33.1.11+ and the controller gRPC service is enabled on the emulator.
排查后的结论
经过多场景测试后发现,这是工作机器的网络管控限制导致的:
- 在物理Android设备上测试,功能完全正常
- 不受公司管控的CI环境中,代码也能正常运行
- 直接在Android Studio内部启动模拟器时,Espresso的旋转API也能正常工作
但公司的网络配置复杂度远超我的处理能力,继续死磕gRPC连接问题显然不现实,只能换个方案实现需求。
有效替代方案:使用UiAutomator实现屏幕旋转
我转而采用UiAutomator来实现屏幕旋转,亲测在受限环境下也能正常工作,代码示例如下:
val device = UiDevice.getInstance(getInstrumentation()) device.setOrientationLandscape()
补充小提示
如果你的环境没有网络管控限制,遇到类似问题时可以先排查这两个基础点:
- 确认Android Emulator版本在33.1.11及以上
- 确认模拟器的gRPC服务已经启用
但如果是和我一样遇到了公司级的网络配置限制,直接切换到UiAutomator会是更高效的解决路径。
内容来源于stack exchange

