Hard and Soft Assert in TestNG

Profile picture for user arilio666

TestNG in selenium is a testing framework used to write and run automated tests. TestNG has the most reliable ability, which is the ability to do assertions.

This allows us to verify the expected behavior of the code.

This article will discuss the two types of Assertion: hard and soft Assertion.

1.) Hard Assertion

Hard assert is a type of Assertion where the execution is stopped once the Assertion fails, and it will never go past the next step of the code until the assertion condition of the previous step is purely satisfied.

int a = 10;
        int b = 20;
        Assert.assertEquals(a, b);
        System.out.println("This part is executed");

We can see here the test stopped after the Assertion failed.
The next part of the print statement is never printed.

2.) Soft Assertion

  • Soft Assert is a type of Assertion that does not stop the execution of the test case as soon as an assertion fails. 
  • In other words, if a soft assert fails, TestNG does not immediately mark the test case as a failure but continues executing the test case until the end. 
  • At the end of the test case, TestNG reports all the assertions that failed.

        
        int a = 10;
        int b = 20;
        SoftAssert softAssert = new SoftAssert();
        softAssert.assertEquals(a, b);
        System.out.println("This part is executed");

We can see that even though the Assertion has failed, the next part of the line has run, and this Assertion is valid when we have to run all the codes and rectify the error as a whole.

Tags