代码改变世界

用例失败后截图

2017-07-16 01:42  清风软件测试开发  阅读(756)  评论(0编辑  收藏  举报
Webdriver take screen shot when case failed use TestNG

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;

  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 plaincopy在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.         }  
    16. }