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,
- Hard Assert
- 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:
- Open the browser
- Navigate to Geeksforgeeks Home page
- Get the Title of the page
- 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(); String actualRersult=driver.getTitle(); String expectedResult= "Lazyroar | 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.