2016-09-23 127 views
0

有典型的解决方案捕获屏幕截图,而@Test失败,但有可能做到这一点@Before/AfterClass/Method失败?TestNG是否有可能捕获@BeforeMethod失败的截图?

为什么我需要那个? - 特别是对于@BeforeMethod,我使用测试类的公共逻辑 - 登录并转到特定页面。

+0

你试图使用'Itestresult'这样,'@AfterMethod \t公共无效takeScreenShotOnFailure(ITestResult的TestResult)抛出IOException异常{ \t \t如果( testResult.getStatus()== ITestResult.FAILURE){ \t \t \t System.out.println(testResult.getStatus()); \t \t \t文件scrFile =((TakesScreenshot)驱动程序).getScreenshotAs(OutputType.FILE); \t \t \t FileUtils.copyFile(scrFile,new File(“D:\\ testScreenShot.jpg”)); \t} \t}'您可以对@BeforeMethod – user1207289

回答

1

你可能要尝试并实现你的情况WebDriverEventListener您可能感兴趣的方法onException这将允许你这样做对代码执行过程中发生的每exeception smthn,也这将是必要使用EventFiringWebDriver添加监听器

这里有一些参考: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/events/WebDriverEventListener.html

https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/events/EventFiringWebDriver.html

+0

使用相同的值,不确定它是否与webdriver相关。这应该是testng相关的解决方案。 – user3535807

0

目前停在覆盖TestNG的ITestListener - onTestSkipped方法。缺点是截图正在采取每个跳过@Test方法。在下面的代码中应该重构,但这是一个很好的开始。注意:你应该包括这个自定义监听到你的testng.xml

@Override 
public void onTestSkipped(ITestResult result) { 
    if(result != null){ 
     String failedTestScreenshotFolder = Paths.get("").toAbsolutePath().toString() + "path/skippedScreenshots/"; 
     WebDriver webDriver = ((TestBase)result.getInstance()).webDriver; 
     File scrFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE); 
     try { 
      String className = result.getTestClass().getName(); 
      FileUtils.copyFile(scrFile, new File(failedTestScreenshotFolder + className.substring(className.lastIndexOf(".") + 1) + "." + result.getMethod().getMethodName() + ".jpg")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
相关问题