Skip to content

Instantly share code, notes, and snippets.

@anandbagmar
Last active January 22, 2022 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anandbagmar/b4182ebbadc42b730c87a868011a350f to your computer and use it in GitHub Desktop.
Save anandbagmar/b4182ebbadc42b730c87a868011a350f to your computer and use it in GitHub Desktop.
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");
}
}
@supertgtline
Copy link

I can't run because the test stuck at java.lang.IllegalStateException: Could not find a soft assertion object but i had
sa = BaseAssertTest.getSoftAssert();
sa.assertEquals( mapLayersPage.verifyCatchesCheckBox(),"true");
and i don't know String testName = null ? What is this variable

@anandbagmar
Copy link
Author

@tgthao - there are now better and easier ways to use soft assertions. Example: You can refer to assertj library for Java which gives you this capability out of the box - https://assertj.github.io/doc/
https://www.baeldung.com/introduction-to-assertj

TestNG also supports soft assertions now - https://www.javadoc.io/doc/org.testng/testng/6.8.8/org/testng/asserts/SoftAssert.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment