The Assertion in TestNG decides the Pass/Fail status of individual Test Methods. Java Assertion is mainly used to take decisions at the code level during execution. Based on that, the flow of the program would be decided.
This can be implemented using the Assert Class or assert keyword. This is not just related to TestNG. It can be used in programs as well for error handling or to avoid error at run time. But, this has been used mostly while working in TestNG Framework.

Assert in main() method
- There are two important points to be considered while using assert:
- By default, assert remains disabled in the Java. So, just writing code is not enough to run assert in the program.
- Assert would only work using a command line argument while using in normal programs having main().
/**
* @author ashok.kumar
*
*/
public class AssertionUse {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int currentNumber=5;
assert currentNumber >= 6:"User number is incorrect.";
System.out.println("test completed.");
}
}
In the above program observe that condition is false and should throw an error while execution. If we directly run the program using Eclipse or try to run it without asserting enabled, it won’t give any error or exception.
Below are the steps to execute the any program on command prompt:
1. Copy the entire code and paste it new Word or notepad Document.
2. Save the document with the Class name, example, “AssertionUse.java“
3. Open the command prompt.
4. Locate folder which contains AssertionUse.java file.
5. type, javac AssertionUse.java and press Enter.
6. type, java AssertionUse and press Enter.
Now, to run the program with enabled assert feature replace point #6 with below line:
6. type, java -ea AssertionUse and press Enter.

Assertion in TestNG
In TestNG, assertions applied on Test Method level. Observe the below code, here we have used assertEquals method of Assert Class. There are two variations present for assertEquals method:
- Assert.assertEquals(<actualResult>, <expectedResult>);
- Assert.assertEquals(<actualResult>, <expectedResult>,”<errorMessage”>);
<actualResult> and <expectedResult>: could be String, int, Boolean, any type of array, object.
<errorMessage>: Any message in String format to display when Assertion gets failed.
- Most commonly used assertions:
- assertEquals
- assertNotEquals
- assertTrue
- assertFalse
- assertNull
- assertNotNull
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author ashok.kumar
*
*/
public class SampleAssertion {
@Test
public void LaunchBrowser()
{
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://google.com");
System.out.println("First URL Launched.");
String currentBrowserTitle=driver.getTitle();
String expectedResult="google";
Assert.assertEquals(currentBrowserTitle, expectedResult);
// Click on Search field and search any string.
driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys("allinoneblogs"+Keys.ENTER);
}
@Test
public void LaunchBrowser2()
{
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://google.com");
System.out.println("Second URL Launched");
String currentBrowserTitle=driver.getTitle();
String expectedResult="Google";
Assert.assertEquals(currentBrowserTitle, expectedResult);
}
@Test(description="Assert with error message.")
public void LaunchBrowser3()
{
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://google.com");
System.out.println("Second URL Launched");
String currentBrowserTitle=driver.getTitle();
String expectedResult="Gmail";
Assert.assertEquals(currentBrowserTitle, expectedResult,"Browser tile mismatch.");
}
}

Hard Assertion
Note, rest of the code in a particular Test Method doesn’t get executed if assertion gets failed. In the above example, for the first test method “LaunchBrowser()“, observe that there was a code snippet to click on the search field and search any string as mentioned below:
// Click on Search field and search any string.
driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys("allinoneblogs"+Keys.ENTER);
Currently, the above line of code doesn’t get executed if the result of assertEquals() is FAIL. This process is called HARD Assertion.
Soft Assertion
There are scenarios where we want that rest of the code get execute even assertion gets failed. To achieve this we have to use SoftAssert Class.
import java.awt.RenderingHints.Key;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
/**
* @author ashok.kumar
*
*/
public class VerifyAssertion {
@Test
public void LaunchBrowser()
{
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://google.com");
System.out.println("First URL Launched.");
String currentBrowserTitle=driver.getTitle();
String expectedResult="google";
SoftAssert softAssert =new SoftAssert();
softAssert.assertEquals(currentBrowserTitle, expectedResult);
driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys("allinoneblogs"+Keys.ENTER);
softAssert.assertAll();
}
}
In the SoftAssertion process, we could use multiple assertions in a single Test Method. At the end of the method, we have to use assertAll(). This method collates the result of all assertEquals() method. If anyone result fails the end result of the test method would also FAIL. To understand this refer below program:
import java.awt.RenderingHints.Key;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
/**
*
*/
/**
* @author ashok.kumar
*
*/
public class VerifyAssertion {
@Test
public void LaunchBrowser()
{
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://google.com");
System.out.println("First URL Launched.");
String currentBrowserTitle=driver.getTitle();
String expectedResult="google";
SoftAssert softAssert =new SoftAssert();
softAssert.assertEquals(currentBrowserTitle, expectedResult);
String searchKey="allinoneblogs";
driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys(searchKey+Keys.ENTER);
currentBrowserTitle=driver.getTitle();
softAssert.assertEquals(currentBrowserTitle, searchKey+" - Google Search");
softAssert.assertAll();
}
}
- softAssert.assertEquals(currentBrowserTitle, expectedResult); : FAIL
- softAssert.assertEquals(currentBrowserTitle, searchKey+” – Google Search”); : PASS
- softAssert.assertAll(); : FAIL
Related Links:
- TestNG – 1 || Introduction and benefits of TestNG Framework.
- TestNG – 2 || Installation process and a sample program of TestNG.
- TestNG – 3 || Create and execute multiple Test Cases.
- TestNG – 4 || Let’s understand @Test Annotation and attributes.
- TestNG – 5 || Understand Assertion in TestNG.
- TestNG – 6 || Use of @BeforeMethod and @AfterMethod.
- TestNG – 7 || Use of @BeforeClass and @AfterClass.
- TestNG – 8 || Creation and execution of Test Suites.
- TestNG – 9 || Let’s move deep into the Test Suites.
- TestNG – 10 || Use @BeforeTest and @AfterTest Annotations.
- TestNG – 11 || Groups attribute with @Test Annotation.
- TestNG – 12 || Use of @BeforeGroups & @AfterGroups.
- TestNG – 13 || Use of @BeforeSuite & @AfterSuite.
- TestNG – 14 || DataProvider annotation & attribute.
- TestNG – 15 || DataProvider with parameters.
- TestNG – 16 || Access data from Excel sheet using DataProvider.
- TestNG – 17 || Passing multiple Parameters in testng xml.
- TestNG – 18 || Multiple Browser and Parallel Execution in TestNG.
- TestNG -19 || Concept of Parallel Execution.
- TestNG – 20 || Run TestNG Program using main() method.
Java Basics:
- Basic Java – 1 || Understand Java before start learning JAVA.
- Basic Java – 2 || Variables and Data Types used in JAVA.
- Basic Java – 3 || Understanding Class, Objects, Methods in Java.
- Basic Java – 4 || More on methods(Return Type and Parameters)
- Basic Java – 5 || Methods- Call by Value and Call by Reference in Java.
- Basic Java – 6 || Understanding of Constructor and Destructor in JAVA.
- Basic Java – 7 || Static Variables and Methods.
- Basic Java – 8 || Lets learn about Arrays in Java.
- Basic Java – 9 || Performing multiple operations using Java Operators.
- Basic Java – 10 || Conditions (If and Switch) in JAVA.
- Basic Java – 11 || for and for-each in Java. (Loops Part-1)
- Basic Java – 12 || Alternate looping concepts while and do-while. (Loops Part-2)
- Basic Java – 13 || Decimal values v/s Octal base(8) values in JAVA.
- Basic Java – 14 || Learn about String literals in Java.
- Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).
- Basic Java – 16 || Runtime User Input using BufferedReader Class (Part-2).
- Basic Java – 17 || Runtime User Input using Console Class (Part-3).
- Basic Java – 18 || Difference between break and continue keywords.
- Basic Java – 19 || Sending Email using Java (Part-1).
- Basic Java – 20 || Sending Email with attachment using Java (Part-2).
- Basic Java – 21 || Stack memory and Heap memory in Java.
- Basic Java – 22 || Let’s learn more about String.
- Basic Java – 23 || String, StringBuffer & StringBuilder in Java.
- Basic Java – 24 || Exception Handling using Try Catch.
- File Handling | Reading data from word document(.doc or .docx) in JAVA.
- File Handling | Reading data from Excel files (.xls or .xlsx) using JAVA.
- File Handling | Writing data into an Excel(.XLSX or .XLS) File.
- File Handling | Implement formatting in Excel using Java.
- File Handling | Copy existing data from one workbook to another workbook in Java.
- File Handling | Reading data from PDF file using JAVA.
- File Handling || Traverse folders and subfolders in Java.
- File Handling || Reading and Writing data from a text file.
- File Handling || Multiple file creation using template based input data.
- Framework || Simple example of Key Driven Framework using excel sheet in Selenium(JAVA).
- QnA || How to use Constructors in Abstract class?
- QnA | Difference between Integer and int keywords.
- QnA | Can main method be overloaded?
- QnA | How do I reverse a String/Sentence in Java?
- QnA | Perform Multiplication and Division without * or / or % operators.
- QnA | How do I get the default value of data type?
- QnA | How to split String if it contains period symbol (.) in between?
- Different ways to Reverse a String in Java.
- Copy formatting & style of cells from one sheet to another.
- Getting IP address and Hostname using InetAddress Class.
- User inputs via Command Prompt using arguments of main() method of a class.
- Program for List and ArrayList in Java.
- Useful methods and implementation under Scanner Class.
- Swapping two variable values without using any third variable.
- Difference between int x= 10 and y=010 in Java.
- Parameterized Constructors v/s Setter and Getter function in JAVA.
- Override a Static Method.
- Computer Basics -13 || Creating pivot charts/tables in Excel.
- Computer Basics -12 || Advantages of PivotCharts over Simple Charts in Excel.
- Computer Basics -11 || Using Charts in place of Data Tables in Excel.
- Computer Basics -10 || How to apply Filter in a data set in Excel?
- Computer Basics -9 || Understand and Implement Data Validation in Excel.
- Computer Basics -8 || Let’s learn the usage of MS-Excel.