Webdriver take screen shot when case failed use TestNG

来源:互联网 发布:汇编数组 编辑:程序博客网 时间:2024/05/16 19:03

Is there a good way to capture screenshots when running tests in parallel on the method level?

In order to run tests in parallel, each individual test needs a unique driver instance. So, at any given time you have x number of driver instances running. When it comes time to capture a screenshot, how do you determine which driver to use?


If you create a base test class with access to the driver, then that driver will always be the correct driver

The following will achieve this;

All test classes must extend a simple base test class;


[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. public asbtract baseTestCase() {  
  2.   
  3.     private WebDriver driver;  
  4.   
  5.     public WebDriver getDriver() {  
  6.             return driver;  
  7. }  
  8.   
  9.     @BeforeMethod  
  10.     public void createDriver() {  
  11.             Webdriver driver=XXXXDriver();  
  12.     }  
  13.   
  14.     @AfterMethod  
  15.         public void tearDownDriver() {  
  16.         if (driver != null)  
  17.         {  
  18.                 try  
  19.                 {  
  20.                     driver.quit();  
  21.                 }  
  22.                 catch (WebDriverException e) {  
  23.                     System.out.println("***** CAUGHT EXCEPTION IN DRIVER TEARDOWN *****");  
  24.                     System.out.println(e);  
  25.                 }  
  26.   
  27.         }  
  28.     }  

In your listener, you need to access the base class;

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. public class ScreenshotListener extends TestListenerAdapter {  
  2.   
  3. @Override  
  4. public void onTestFailure(ITestResult result)  
  5. {  
  6.         Object currentClass = result.getInstance();  
  7.         WebDriver webDriver = ((BaseTest) currentClass).getDriver();  
  8.   
  9.         if (webDriver != null)  
  10.         {  
  11.   
  12.            File f = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);  
  13.   
  14.            //etc.   
  15.         }  

0 0