Open In App

How to Use Soft Asserts in TestNG?

Last Updated : 28 Sep, 2022
Like Article

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

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

import org.testng.asserts.SoftAssert;

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,

  • AssertEquals
  • AssertTrue
  • AssertFalse
  • AssertNotEquals

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).


import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import org.openqa.selenium.By;
public class Geeks {
    public void geekforgeeks() throws InterruptedException {
        ChromeDriver driver = new ChromeDriver();
        SoftAssert softAssert = new SoftAssert();
        String actualRersult=driver.getTitle();
        String expectedResult="GeeksforGeeks ";
        softAssert.assertEquals(actualRersult,expectedResult,"Title is not Matching");

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,


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads