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的一個(gè)監(jiān)聽(tīng)器來(lái)監(jiān)聽(tīng)錯(cuò)誤時(shí)截圖:
public class DotTestListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult tr) {
}
}
3.也是說(shuō)我們只需要在onTestFailure方法里面調(diào)用ScreenShot類里面的takeScreenshot方法即可,但是我們注意到ScreenShot類里需要傳一個(gè)driver進(jìn)去。
現(xiàn)在問(wèn)題來(lái)了,對(duì)于driver的處理,各式各樣,有的用到了單子模式,即把driver當(dāng)成一個(gè)全局的靜態(tài)變量,在哪都可以用,所以ScreenShot類里可以訪問(wèn)得到driver對(duì)象,但這樣也有一個(gè)問(wèn)題,即全局只有一個(gè)driver,如果想多線程運(yùn)行時(shí),啟多個(gè)driver實(shí)例時(shí),用這種方式做不到了,于是出現(xiàn)了另外一種處理方式,即每一個(gè)類或者每一個(gè)測(cè)試方法是,啟一個(gè)新的driver對(duì)象,這樣,driver對(duì)象不是全局的了,是類對(duì)象屬性了,比如:
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);
}
}