A good option is to use an ITestListener
instead of handling failure reporting in @AfterMethod
. The test listener's onTestFailed()
function will be called after your test method has run, but before the @AfterMethod
method has run. (Note that there is not an onTestFinished()
function in the listener; that role is fulfilled by @AfterMethod
.)
To make things easier on yourself, you can use a TestListenerAdapter
, which will implement all of the other functions that you don't specifically @Override
yourself.
What you end up with is:
public class MyTestListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult result){
yourTakeScreenShotFunctionHere();
}
}
You then attach the listener to your test class with
@Listeners({MyTestListener.class})
public class MyTestClass(){etc}
The ITestResult
is a reference to your test class's object, so you can use reflection to grab data out of it such as a Selenium WebDriver instance, etc.
You can have as many different listeners as you want, to do various things such as clean up or preserve error logs, take screenshots, trigger other reporting functionality, send emails, or whatever you want.