testng對失敗時截圖處理

1.截圖類:java

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的一個監聽器來監聽錯誤時截圖:多線程

public class DotTestListener extends TestListenerAdapter {

	@Override
	public void onTestFailure(ITestResult tr) {		
		
	}

}

 3.也就是說咱們只須要在onTestFailure方法裏面調用ScreenShot類裏面的takeScreenshot方法便可,可是咱們注意到ScreenShot類裏須要傳一個driver進去。ide

如今問題來了,對於driver的處理,各式各樣,有的用到了單子模式,即把driver當成一個全局的靜態變量,在哪均可以用,因此ScreenShot類裏能夠訪問獲得driver對象,但這樣也就有一個問題,即全局只有一個driver,若是想多線程運行時,啓多個driver實例時,用這種方式就作不到了,因而出現了另一種處理方式,即每個類或者每個測試方法是,啓一個新的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);
	}	
	
}

 那如何把這個類對象的driver屬性給傳到onTestFailure方法裏去?ui

public class DotTestListener extends TestListenerAdapter {

	@Override
	public void onTestFailure(ITestResult tr) {		
		try {
			TestBase tb = (TestBase) tr.getInstance();
			WebDriver driver = tb.getDriver();			
			System.out.println(driver.getTitle());
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {			
			e.printStackTrace();
		}
	}

}

 最後再加上監聽便可:this

@Listeners({ DotTestListener.class })
public class Test10 extends TestBase{	
	
	@Test
	public void testInput(){
		System.out.println(5/0);
	}	
	
}
相關文章
相關標籤/搜索