Open In App

How to Use Hard Asserts in TestNG?

Last Updated : 15 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

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.

Java




import org.testng.Assert;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeDriver;
  
public class Geeks {
    @Test
    public void geekforgeeks() {
        ChromeDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.geeksforgeeks.org/");
        String actualRersult=driver.getTitle();
      
        String expectedResult="GeeksforGeeks | A computer science portal for geeks";
        Assert.assertEquals(actualRersult, expectedResult);
  
        driver.close();      
    }
}


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.

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads