Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Soft Assertion implementation using TestNG
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.asserts.SoftAssert;
public class BaseTest implements IHookable {
String testName = null;
private static final String SOFT_ASSERT = "softAssert";
@Override
public void run(IHookCallBack callBack, ITestResult testResult) {
SoftAssert softAssert = new SoftAssert();
testResult.setAttribute(SOFT_ASSERT, softAssert);
callBack.runTestMethod(testResult);
softAssert = getSoftAssert(testResult);
if (!testResult.isSuccess()) {
Throwable throwable = testResult.getThrowable();
if (null != throwable) {
if (null != throwable.getCause()) {
throwable = throwable.getCause();
}
softAssert.assertNull(throwable, ExceptionUtils.getStackTrace(throwable));
}
}
softAssert.assertAll();
}
public static SoftAssert getSoftAssert() {
return getSoftAssert(Reporter.getCurrentTestResult());
}
private static SoftAssert getSoftAssert(ITestResult result) {
Object object = result.getAttribute(SOFT_ASSERT);
if (object instanceof SoftAssert) {
return (SoftAssert) object;
}
throw new IllegalStateException("Could not find a soft assertion object");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment