//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使用,可以更好的提高代码的健壮性;