Java移动端测试如何切换横竖屏?DesiredCapabilities配置无效怎么解决
问题根因
- Chrome移动模拟模式下,
rotatable、deviceOrientation这两个配置不会读取DesiredCapabilities的顶层参数,必须放到mobileEmulation实验配置项内部才会生效 - 最新版本Selenium已经不推荐直接使用DesiredCapabilities后再merge到ChromeOptions的写法,所有配置优先直接写到ChromeOptions中
启动时固定横竖屏的正确代码
Map<String, Object> mobileEmulator = new HashMap<>(); mobileEmulator.put("deviceName", deviceName); // orientationMode可传入"portrait"(竖屏)或"landscape"(横屏) mobileEmulator.put("deviceOrientation", orientationMode); WebDriverManager.chromedriver().setup(); ChromeOptions chromeOption = new ChromeOptions(); chromeOption.setPageLoadStrategy(PageLoadStrategy.NONE); chromeOption.setExperimentalOption("mobileEmulation", mobileEmulator); // 无需额外定义DesiredCapabilities,直接传ChromeOptions即可 driver = new ChromeDriver(chromeOption);
运行时动态切换横竖屏的实现
如果需要在测试执行过程中切换横竖屏,可通过Chrome DevTools协议实现:
// 切换为横屏示例 Map<String, Object> params = new HashMap<>(); params.put("width", 1920); params.put("height", 1080); params.put("deviceScaleFactor", 100); params.put("mobile", true); params.put("screenOrientation", Map.of( "type", "landscapePrimary", "angle", 90 )); ((ChromeDriver) driver).executeCdpCommand("Emulation.setDeviceMetricsOverride", params); // 切换为竖屏示例 params.put("width", 1080); params.put("height", 1920); params.put("screenOrientation", Map.of( "type", "portraitPrimary", "angle", 0 )); ((ChromeDriver) driver).executeCdpCommand("Emulation.setDeviceMetricsOverride", params);
注意事项
- 确认
orientationMode的取值拼写正确,必须是全小写的portrait或landscape - 如果你使用的是真机测试而非Chrome自带的移动端模拟功能,需要接入Appium对应的横竖屏切换API,ChromeDriver仅支持自身模拟的设备配置修改
内容的提问来源于stack exchange,提问作者Rasika Thakare
相关产品推荐
相关产品推荐

