Customize SoftAssert in TestNG
In this post, we will see how to customize SoftAssert in the TestNG Framework. Let’s first run all assertions and capture screenshots for all failed assertions in a test method. Then, to modify the default behavior subclasses, we should override various hooks provided by the Assertion class.
Basic things
SoftAssert just records the failure when an assertion fails. Calling .assertAll() will cause an exception to be thrown if at least one assertion has failed in our test. It just like collecting errors while assertion.
protected void doAssert(IAssert<?> a) { ..... }
IAssert is an interface in TestNG for the assert command. It has specifications for getting assert messages, doAssert, getActual and getExpected.
CustomSoftAssert
public class CustomSoftAssert extends SoftAssert { ..... ..... }
Our CustomSoftAssert would retain doAssert() and .assertAll() but hooks custom implementation to capture screenshot by overriding below method:
@Override public void onAssertFailure(IAssert<?> assertCommand, AssertionError ex) { // taking screenshot code goes here ..... }
TestNG allows you to extend Assertion and do some custom implementation as opposed to default framework behavior. By this approach, we can hook some piece of code ( custom implementations ). We can hook or override methods for alternative implementation. For example, the capture screenshot code can be hooked to CustomSoftAssert().
Instantiate Class
CustomSoftAssert customsoftassert = new CustomSoftAssert();
Sample test method
@Test public void sampleTilteFailureTests() { System.setProperty("webdriver.edge.driver", "MicrosoftWebDriver.exe"); driver=new EdgeDriver(); CustomSoftAssert csa = new CustomSoftAssert(); driver.get("https://www.bing.com/"); driver.manage().window().maximize(); WebDriverWait wait = new WebDriverWait(driver, 120); wait.until(ExpectedConditions.titleContains("Bing")); csa.assertEquals("BogusTitle", driver.getTitle(), "Assert1,this will fail"); driver.get("https://start.duckduckgo.com/"); driver.manage().window().maximize(); WebDriverWait wait1 = new WebDriverWait(driver, 120); wait1.until(ExpectedConditions.titleContains("Duck")); csa.assertEquals("BogusTitle", driver.getTitle(), "Assert2,this too will fail"); csa.assertAll(); }
TestNG Tutorials on this website can be found at:
For more details on the TestNG Framework, visit the official website of TestNG at: