Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect test failure in testng @AfterMethod

Tags:

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?

like image 619
Ingo Kegel Avatar asked Sep 03 '13 17:09

Ingo Kegel


People also ask

How to rerun failed Test cases in TestNG?

By overriding retry() method of the interface in your class, you can control the number of attempts to rerun a failed test case. Now if we run TestNG. xml we see failed test case is executed one more time as we gave retry count= 1. Test case is marked as failed only after it reaches max retry count.

What is AfterMethod in TestNG?

The @AfterMethod annotation is specific to a class not to an XML file. The @AfterMethod annotated method will be invoked after the execution of each test method. Suppose there are four test methods means that @AfterMethod annotated method will be executed four times.

How do you stop TestNG from running after a test fail?

It depends on what you expect (there is no direct support for this in TestNG). You can create ShowStopperException which is thrown in @Test and then in your ITestListener implementation (see docs) you can call System.


1 Answers

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
   }        
}
like image 63
JacekM Avatar answered Sep 28 '22 00:09

JacekM