I am having multiple assertions (assertTrue) in my test method, I want to pass the assertion failure to my @AfterMethod on which ever assertion my test failed so that I can get the exact location where my API test failed. Is there any way to achieve this? Using Rest assured, Maven & TestNG.
Every @AfterMethod
can accept a ITestResult
as a parameter, which TestNG during execution natively injects the test result of the last @Test
. So you can examine the ITestResult
object and then proceed further.
Here's a simple sample
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
public class SampleTestClass {
@Test
public void passMethod() {
Assert.assertTrue(true);
}
@Test
public void failMethod() {
Assert.assertTrue(false);
}
@AfterMethod
public void afterMethod(ITestResult testResult) {
if (testResult.isSuccess()) {
return;
}
Throwable throwable = testResult.getThrowable();
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
throwable.printStackTrace(writer);
System.err.println("****" + sw.getBuffer().toString());
}
}