Detect test failure in testng @AfterMethod

Ingo Kegel picture Ingo Kegel · Sep 3, 2013 · Viewed 19.5k times · Source

I want to take a screenshot if a test fails. Rather than wrapping all test methods with try/catch blocks, I would like to add this logic to the method annotated with @AfterMethod.

How can I detect in the method annotated with @AfterMethod if the current test has failed?

Answer

JacekM picture JacekM · Sep 3, 2013

If the method annotated with @AfterMethod has an ITestResult parameter then TestNG will automatically inject the result of the test. (source: TestNG documentation, section 5.18.1)

This should do the job:

@AfterMethod
public void tearDown(ITestResult result) {
   if (result.getStatus() == ITestResult.FAILURE) {
      //your screenshooting code goes here
   }        
}