Assertions in our test suites are required to validate the actual result with 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 failure.
But many times we might require the test method to continue execution even after the failure of the first assertion statement. Requirement like these arise 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.
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 assertion 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.
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.