1.截圖類:
public class ScreenShot {
public WebDriver driver;
public ScreenShot(WebDriver driver) {
this.driver = driver;
}
private void takeScreenshot(String screenPath) {
try {
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(screenPath));
} catch (IOException e) {
System.out.println("Screen shot error: " + screenPath);
}
}
public void takeScreenshot() {
String screenName = String.valueOf(new Date().getTime()) + ".jpg";
File dir = new File("test-output/snapshot");
if (!dir.exists())
dir.mkdirs();
String screenPath = dir.getAbsolutePath() + "/" + screenName;
this.takeScreenshot(screenPath);
}
}
2.我們可以用testng的一個監(jiān)聽器來監(jiān)聽錯誤時截圖:
public class DotTestListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult tr) {
}
}
3.也是說我們只需要在onTestFailure方法里面調(diào)用ScreenShot類里面的takeScreenshot方法即可,但是我們注意到ScreenShot類里需要傳一個driver進(jìn)去。
現(xiàn)在問題來了,對于driver的處理,各式各樣,有的用到了單子模式,即把driver當(dāng)成一個全局的靜態(tài)變量,在哪都可以用,所以ScreenShot類里可以訪問得到driver對象,但這樣也有一個問題,即全局只有一個driver,如果想多線程運(yùn)行時,啟多個driver實例時,用這種方式做不到了,于是出現(xiàn)了另外一種處理方式,即每一個類或者每一個測試方法是,啟一個新的driver對象,這樣,driver對象不是全局的了,是類對象屬性了,比如:
public class TestBase {
public WebDriver driver;
public WebDriver getDriver() {
return driver;
}
@BeforeClass
public void setUp(){
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.baidu.com");
}
@AfterClass
public void tearDown(){
driver.close();
driver.quit();
}
}
public class Test10 extends TestBase{
@Test
public void testInput(){
System.out.println(5/0);
}
}