Site icon TestingDocs.com

Customize SoftAssert in TestNG

Introduction

In this post, we will see how to customize SoftAssert in TestNG Framework.  ( SoftAssert in TestNG Framework ). We will try to customize SoftAssert. Lets us see how to run all asserts and capture screenshots for all failed asserts in a test method. To modify the default behavior sub classes we should override various hooks provided by the Assertion class.

Taking screenshot when an Assert fails in TestNG tests.

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:

https://www.testingdocs.com/testng-framework-tutorial/

For more details on the TestNG Framework, visit the official website of TestNG at:

https://testng.org

Exit mobile version