1.截图类:
1 public class ScreenShot { 2 public WebDriver driver; 3 4 public ScreenShot(WebDriver driver) { 5 this.driver = driver; 6 } 7 8 private void takeScreenshot(String screenPath) { 9 try { 10 File scrFile = ((TakesScreenshot) driver) 11 .getScreenshotAs(OutputType.FILE); 12 FileUtils.copyFile(scrFile, new File(screenPath)); 13 } catch (IOException e) { 14 System.out.println("Screen shot error: " + screenPath); 15 } 16 } 17 18 public void takeScreenshot() { 19 String screenName = String.valueOf(new Date().getTime()) + ".jpg"; 20 File dir = new File("test-output/snapshot"); 21 if (!dir.exists()) 22 dir.mkdirs(); 23 String screenPath = dir.getAbsolutePath() + "/" + screenName; 24 this.takeScreenshot(screenPath); 25 } 26 }
2.我们可以用testng的一个监听器来监听错误时截图:
1 public class DotTestListener extends TestListenerAdapter { 2 3 @Override 4 public void onTestFailure(ITestResult tr) { 5 6 } 7 8 }
3.也就是说我们只需要在onTestFailure方法里面调用ScreenShot类里面的takeScreenshot方法即可,但是我们注意到ScreenShot类里需要传一个driver进去。
现在问题来了,对于driver的处理,各式各样,有的用到了单子模式,即把driver当成一个全局的静态变量,在哪都可以用,所以ScreenShot类里可以访问得到driver对象,但这样也就有一个问题,即全局只有一个driver,如果想多线程运行时,启多个driver实例时,用这种方式就做不到了,于是出现了另外一种处理方式,即每一个类或者每一个测试方法是,启一个新的driver对象,这样,driver对象就不是全局的了,就是类对象属性了,比如:
1 public class TestBase { 2 3 public WebDriver driver; 4 5 public WebDriver getDriver() { 6 return driver; 7 } 8 9 @BeforeClass 10 public void setUp(){ 11 driver = new FirefoxDriver(); 12 driver.manage().window().maximize(); 13 driver.navigate().to("http://www.baidu.com"); 14 } 15 16 @AfterClass 17 public void tearDown(){ 18 driver.close(); 19 driver.quit(); 20 } 21 }
1 public class Test10 extends TestBase{ 2 3 @Test 4 public void testInput(){ 5 System.out.println(5/0); 6 } 7 8 }
那如何把这个类对象的driver属性给传到onTestFailure方法里去?
1 public class DotTestListener extends TestListenerAdapter { 2 3 @Override 4 public void onTestFailure(ITestResult tr) { 5 try { 6 TestBase tb = (TestBase) tr.getInstance(); 7 WebDriver driver = tb.getDriver(); 8 System.out.println(driver.getTitle()); 9 } catch (SecurityException e) { 10 e.printStackTrace(); 11 } catch (IllegalArgumentException e) { 12 e.printStackTrace(); 13 } 14 } 15 16 }
最后再加上监听即可:
1 @Listeners({ DotTestListener.class }) 2 public class Test10 extends TestBase{ 3 4 @Test 5 public void testInput(){ 6 System.out.println(5/0); 7 } 8 9 }
感谢分享:http://www.cnblogs.com/zhangfei
注:转载需注明出处及作者。