背景:最開始用手機模拟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("使用浏覽器,進入到了百度頁面");
}
效果如圖: