TestNG is a testing framework inspired by JUnit but introducing a whole set of new functionalities. Let's see in this TestNG Hello world example how to use it.

TestNG is an open source automated testing framework. It has been designed to reduce some of the limitations of JUnit to make it more flexible and powerful. The highlights of TestNG are:

  • TestNG supports a wide range of annotations.
  • TestNG uses more Java and OO features.
  • TestNG supports testing integrated classes (i.e. by default, no need to create a new test class instance for every test method).
  • TestNG has a clean separation from compile-time test code and run-time configuration/data info.
  • TestNG supports a flexible runtime configuration.
  • TestNG introduces the concept of ‘test groups’. Once you have compiled your tests, you can just ask TestNG to run all the "front-end" tests, or "fast", "slow", "database" tests, etc.
  • TestNG supports Dependent test methods, parallel testing, load testing, and partial failure.
  • TestNG has a flexible plug-in API.
  • TestNG has support for multi threaded testing.

Let's write a proof of concept Hello World example with TestNG. In order to use it, include in your pom.xml the following dependency:

  <dependencies>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>7.0.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

On the other hand, if you are using Gradle, you will need the following basic configuration in your build.gradle file:

test { //this is the gradle task to be executed
  useTestNG() { //Tells Gradle to use TestNG
       useDefaultListeners = true // Tells TestNG to execute its default reporting structure
       suites 'src/test/suite.xml' //location of our suite.xml
  }
}

Here is your example App.java file:

package com.example;

 
public class App 
{

    public int sum(int a, int b) {
        return a+b;
    }
    
}

Now let's test it with TestNG:

package com.example;


import org.testng.Assert;
import org.testng.annotations.Test;

public class AppTest 
{

    @Test
    public void testExample() {
       App a = new App();

       Assert.assertEquals(10, a.sum(5,5));
    }
}

Run it!

testng tutorial hello world testng

That's it! You have just executed your first HelloWorld TestNG example

FREE WildFly Application Server - JBoss - Quarkus - Drools Tutorials