Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Use Hard Asserts in TestNG?

Improve Article
Save Article
Like Article
  • Last Updated : 15 Sep, 2022
Improve Article
Save Article
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.

What are Asserts?

To check whether the test failed or passed during the testing, the TestNG provides an Assert method in which we can compare the Actual result with the expected result if both match the TestNG test is marked as pass otherwise it is marked as fail. There are two types of Asserts provided in the TestNG,

  1. Hard Assert
  2. Soft Assert

1. Hard Assert

Hard Asserts are the type of assets that stop the execution of the program when the condition becomes fail and mark the Test as Failed. It is used when the validation of one element is necessary to perform any other upcoming actions. For example login functionality which is essential to perform any other tests. It is the default type of Assert provided by TestNG.

2. Soft Assert

Soft Asserts are the type of assets that continue executing the sequent lines of code even if the Assert is failed.

Using Hard Assert in TestNG

Let’s see the usage and working of Hard Assert in TestNG by executing a test case. Take the Scenario:

  1. Open the browser
  2. Navigate to Geeksforgeeks Home page
  3. Get the Title of the page
  4. Check the title with the expected result using Assert.

The Assert class provides many methods such as,

  • Assert.assertEqual(String actualResult, String expectedResult);
  • Assert.assertEqual(String actualResult, String expectedResult, message);
  • Assert.assertTrue(condition);
  • Assert.assertTrue(condition, message);

Let’s execute using the 1st Method


Assert.assertEqual(actualResult, ExpectedResult);

It requires two parameters, one for the actual result and another one for the expected result. It compares both and throws the exception when it fails.


import org.testng.Assert;
import org.testng.annotations.Test;
public class Geeks {
    public void geekforgeeks() {
        ChromeDriver driver = new ChromeDriver();
        String actualRersult=driver.getTitle();
        String expectedResult="GeeksforGeeks | A computer science portal for geeks";
        Assert.assertEquals(actualRersult, expectedResult);

The above will compare both actual and expected results and return the Test as passed. If there is not a match the test is marked as fail along with an exception is thrown, and the code below the asset is not Executed.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!