How to Use Soft Asserts in TestNG?
TestNG is an open source automation framework that is used to perform software testing more easily, it provides various annotations and is used to perform parallel testing and produce the test reports. TestNG provides asserts to check the actual results with the expected results, Asserts are necessary to validate a test case, whether it is a pass or a fail, There are two types of asserts provided by TestNG, Hard assert and Soft Assert. Hard asserts stop the execution of code when the asserts fail.
Soft asserts are the asserts which continue the execution even after the Assert condition fails. Soft asserts are mainly used to verify certain test conditions in the code. It is used in a case when the passing of one test condition is not necessary to execute the upcoming tests. It is not included by default in TestNG, In order to use the soft assert, we have to import package from TestNG.
Creating Instance for Soft Assert:
softAssert softAssert = new SoftAssert();
After creating the instance for the soft assert, import the package
In the end, we have to call the assertAll() method that is used to throw the exceptions and results at the end of the test.
Soft Assert also supports all the methods used by Hard Asserts such as,
Let’s see the usage and working of the SoftAssert by executing a test case,
- Open the browser
- Navigate to Geeksforgeeks Home page
- Get the Title of the page
- Check the title with the expected result using Assert.
- Click on Java from the menu.
In this code, we are using the method assertEqual(String actualResult, String expectedResult, message).
In this code, the actual and expected value are not matching, even if the exception is not thrown during the execution, and all the below lines are also executed. After calling the assertAll() method, the assert throws the exception and the test is marked as Failed. The output of the above code is,