Use of Soft assertion in TestNG

Posted By :Nidhi Ojha |29th April 2020

Assertions in our test suites are required to validate the actual result with the expected result. The Assert class given by TestNG provides a form of hard assertion wherein once assertion fails the execution of that specific test method stops and the test method is decided as failure.

But many times we might need the test method to continue execution even though the failure of the first assertion statement. Requirement like these emerge when we have collective assertions in our test method or we want to execute various other line of codes after the assertion statement. For handling these type of cases, TestNG gives a SoftAssert class.

 

SoftAssert softAssert = new SoftAssert();

 

At the time when we use SoftAssert, inclose of assertion failure assertionException is not thrown out rather all the statements are executed and afterward the test accumulates the result of all the assertions and marks the test case as passed or failed on the basis of assertion result.

 

In the below written code snippet, we are operating three assertion within the test method. We are deliberately failing the first two assertions however the whole test method will get executed. The last statement softAssert.assertAll() is very important, it will accumulate the result of all the assertions and inclose of any failure mark, the test as failed.

 

PS: If we don’t use softAssert.assertAll(), then the test case will be decided as passed even in case of assertion failure.

 

Code Snippet:

@Test
public void softAssertionTest(){
//Creating softAssert object
SoftAssert softAssert = new SoftAssert();
//Assertion failing
softAssert.fail("Failing first assertion");
System.out.println("Failing 1");
//Assertion failing
softAssert.fail("Failing second assertion");
System.out.println("Failing 2");
//Assertion passing
softAssert.assertEquals(1, 1, "Passing third assertion");
System.out.println("Passing 3");
//Collates the assertion results and marks test as pass or fail
softAssert.assertAll();
}


Output:

Failing 1
Failing 2
Passing 3


Failure Exception:

FAILED: softAssertionTest
java.lang.AssertionError: The following asserts failed:
 Failing first assertion,
 Failing second assertion
 at org.testng.asserts.SoftAssert.assertAll(SoftAssert.java:43)
.....


Here, we can notice that the console output consist of all the print statements even after the assertions are failing. Also, we can observe that the assertion messages hint that two out of the three assertions failed – Failing first assertion, Failing second assertion.


About Author

Nidhi Ojha

Nidhi is certified in Manual Testing and SQL. She has done B.tech in Electronics and Communication branch, apart from this she loves to travel to different places.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us