Soft Assertion in TestNG

Soft Assertion in TestNG

Assertions in our test suites are required to validate the actual result with the expected result. The Assert class provided by TestNG provides a form of hard assertion wherein as soon as an assertion fails the execution of that particular test method stops and the test method is marked as a failure.
But many times we might require the test method to continue execution even after the failure of the first assertion statement. A requirement like these arises when we have multiple assertions in our test method or we want to execute some other line of codes after the assertion statement. For handling these cases, TestNG provides a SoftAssert class.

SoftAssert softAssert = new SoftAssert();

When we use SoftAssert, in case of assertion failure assertionException is not thrown instead all the statements are executed and later the test collates the result of all the assertions and marks the test case as passed or failed based on the assertion result.

In the below code snippet, we are using three assertions within the test method. We are intentionally failing the first two assertions still the whole test method will get executed. The last statement softAssert.assertAll() is very important, it will collate the result of all the assertions and in case of any failure mark, the test as failed.
PS: If we don’t use softAssert.assertAll(), then the test case will be marked 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 observe that the console output contains all the print statements even though the assertions are failing. Also, we can see that the assertion messages imply that two out of the three assertions failed – Failing first assertion, Failing second assertion.

От QA genius

Adblock
detector