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?
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.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With