背景:最开始用手机模拟H5页面跑自动化,发现经常因为app连接或者网络原因等一系列情况,导致M版(H5页面)用例跑不通,想通过浏览器自带的手机模拟器运行,保证稳定性
浏览器自带的模拟器如下图:
代码实现逻辑
public class runtest { WebDriver driver; @BeforeClass public void beforeClass(){ System.setProperty("webdriver.chrome.driver", "resources/chromedriver.exe"); Map<String, String> mobileEmulation = new HashMap<String, String>(); //设置设备,例如:Google Nexus 7/Apple iPhone 6 //mobileEmulation.put("deviceName", "Google Nexus 7"); mobileEmulation.put("deviceName", "Apple iPhone 6 Plus"); //这里是要使用的模拟器名称,就是浏览器中模拟器中的顶部型号 Map<String, Object> chromeOptions = new HashMap<String, Object>(); chromeOptions.put("mobileEmulation", mobileEmulation); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); try { System.out.println("开始启动driver~~~"); driver = new ChromeDriver(capabilities); System.out.println("启动driver成功~~~"); } catch (Exception e) { System.out.println("启动driver失败~~~"); System.out.println(e.getMessage()); } } @Test public void run(){ driver.get("http://m.baidu.com/"); System.out.println("使用浏览器,进入到了百度页面"); }
效果如图: