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的一个监听器来监听错误时截图:
public class DotTestListener extends TestListenerAdapter { @Override public void onTestFailure(ITestResult tr) { } }
3.也就是说我们只需要在onTestFailure方法里面调用ScreenShot类里面的takeScreenshot方法即可,但是我们注意到ScreenShot类里需要传一个driver进去。
现在问题来了,对于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方法里去?
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(); } } }
最后再加上监听即可:
@Listeners({ DotTestListener.class }) public class Test10 extends TestBase{ @Test public void testInput(){ System.out.println(5/0); } }
转载地址:http://www.cnblogs.com/zhangfei/p/4271923.html