//Web頁面截圖
public class ScreenShot {
private WebDriver driver;
public String projectpath=System.getProperty("user.dir");//獲取項目地址
public String scrpath=projectpath+"\\screenShot\\";
public ScreenShot(WebDriver driver) {
this.driver=driver;
}
public void getScreenShot(){
Date currentTime=new Date();//獲取系統當前時
SimpleDateFormat dataFormat=new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");//設置日期格式
String dataString=dataFormat.format(currentTime);
System.out.println("當前時間是:"+dataString);
try{
File srcFile = ((RemoteWebDriver) driver).getScreenshotAs(OutputType.FILE);
File srcseenshot=new File(scrpath+dataString+".jpg");
Files.copy(srcFile, srcseenshot);
}catch(Exception e){
System.out.println("保存截圖失敗");
e.printStackTrace();
}finally{
System.out.println("截圖已保存至:"+scrpath+dataString+".jpg");
}
}
}
//獲取Toast信息(ScreenShot類和Toast類結合使用)
public class Toast {
public ScreenShot sc;
public WebDriver driver;
public Toast(WebDriver driver) {
this.driver=driver;
sc=new ScreenShot(driver);
}
public void getToast(String toastLoc,String expectValue) {
try {
WebElement elementText=driver.findElement(By.xpath(toastLoc));
Thread.sleep(1000);
tring actualValue = elementText.getText();
System.out.println(actualValue);
Assert.assertEquals(actualValue, expectValue);
System.out.println("Toast提示信息校驗成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("未獲取到Toast提示信息,斷言失敗");
sc.getScreenShot();//截圖
}
}
}
說明:獲取toast之前,最好先判斷頁面上的元素是否存在,調用顯示等待WebDriverWait()方法,結合ExpectedConditions使用,可以更好的提高代碼的健壯性;