Reputation: 268
There are typical solutions for capturing screenshot while @Test
failing, but is it possible to do that on @Before/After
Class/Method
fail?
Why I need that? - It will be good especially for @BeforeMethod
where I use common logic for test class - login and go to specific page.
Upvotes: 3
Views: 877
Reputation: 77
For @Before annotation, you could make a workaround by putting screenshots in public void onTestSkipped(final ITestResult result) because when you get any failure in Before methods, all @Test will be skipped and onTestSkipped will be invoked.
That's how I solved it in my project :)
Upvotes: 0
Reputation: 268
currently stops on overriding TestNG ITestListener
- onTestSkipped
method. cons is that screenshots are taking for each skipped @Test
method. offcourse, below code should be refactored, but it's a good point to start. note: you should include this custom listener into your 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();
}
}
}
Upvotes: 0
Reputation: 665
You may want to try and implement WebDriverEventListener
in your case you may be interested in method onException
which will allow you to do smthn on every exeception that occurs during code execution, also it'll be necessary to use EventFiringWebDriver
to add listener
Here are some references: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/events/WebDriverEventListener.html
Upvotes: 1