I am trying to find out a way if there is any way in TetstNG to mark a test method annotated with @Test
as failed inside @AfterMethod
.
@Test
public void sampleTest() {
// do some stuff
}
@AfterMethod
public void tearDown() {
// 1st operation
try {
// some operation
} catch(Exception e) {
// mark sampleTest as failed
}
// 2nd operation
try {
// perform some cleanup here
} catch (Exception e) {
// print something
}
}
I have some verification to be done in all tests, which I am doing under 1st try-catch
block in tearDown()
. If there is an exception in that block, mark the test as failed. Then proceed for next try-catch
block.
I cannot reverse the order of try-catch blocks in tearDown()
because, 1st block depends on 2nd.
To the best of my knowledge you cannot do it from within @AfterMethod
configuration method, because the ITestResult object that gets passed to your configuration method [ Yes you can get access to the test method's result object by adding a parameter ITestResult result
to your @AfterMethod
annotated method ] is not used to update back the original test method's result.
But you can easily do this if you were to leverage the IHookable
interface. You can get more information on IHookable
by referring to the official documentation here .
Here's an example that shows this in action.
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.Test;
public class TestClassSample implements IHookable {
@Test
public void testMethod1() {
System.err.println("testMethod1");
}
@Test
public void failMe() {
System.err.println("failMe");
}
@Override
public void run(IHookCallBack callBack, ITestResult result) {
callBack.runTestMethod(result);
if (result.getMethod().getMethodName().equalsIgnoreCase("failme")) {
result.setStatus(ITestResult.FAILURE);
result.setThrowable(new RuntimeException("Simulating a failure"));
}
}
}
Note: I am using TestNG 7.0.0-beta7
(latest released version as of today)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.