How to add custom messages to TestNG failure?

TestNG supports a lot of assertions. It has the org.testng.Assert class, which extends the Java object class java.lang.object. Whenever there is a failure, the user wants to get a customized failure message so that the root-cause analysis could be easy. TestNG supports assertion with customized failure message. However, message is completely optional.

The syntax is −

Assert.<assertMethod>(expected, actual, message)

If the user doesn't provide a message, TestNG prints a default error message; but if the user sets a message, then TestNG throws the error along with the customized message set by the user.

In this article, we will see how to set a custom message to a TestNG failure.

Approach/Algorithm to solve this problem

  • Step 1 − Create a TestNG class, NewTestngClass.

  • Step 2 − Write three different @Test methods in the class to get failed at three different assertions as shown in the programming code section below.

  • Step 3 − Create the testNG.xml as given below to run the TestNG classes.

  • Step 4 − Finally, run the testNG.xml or directly TestNG class in IDE or compile and run it using command line.


Use the following code for the commonTestNG class, NewTestngClass


import org.testng.Assert;
import org.testng.annotations.*;

public class NewTestngClass {
   public void test1() {
      System.out.println("Running test1");
      int Id = 1;
      int newId = 2 ;
      Assert.assertEquals(Id, newId,"Assert equals validation between id and newId");
   public void test2() {
      System.out.println("Running test2");
      String Id = null;
      Assert.assertNotNull(Id, "Assert not null validation for Id is failed. Id is null");
   public void test3() {
      System.out.println("Running test3");
      Boolean Id = false;
      Assert.assertTrue(Id,"Assert True validation failed as Id is not set to true");


This is a configuration file that is used to organize and run the TestNG test cases. It is very handy when limited tests are needed to execute rather than the full suite.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "" >

<suite name = "Suite1">
   <test name = "test1">
         <class name = "NewTestngClass"/>


Running test1
java.lang.AssertionError: Assert equals validation between id
and newId expected [2] but found [1]
Expected :2
Actual :1
Running test2
java.lang.AssertionError: Assert not null validation for Id is
failed. Id is null expected object to not be null
Running test3
java.lang.AssertionError: Assert True validation failed as Id
is not set to true expected [true] but found [false]
Expected :true
Actual :false