TestNG Introduction and Example

1 - Introduction

TestNG is a testing framework focused on providing both unit and functional testing abilities in the Java programming language. It supports parallel testing, data providers, dependencies, groups and other features.

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use, such as:

  1. Annotations.
  2. Run your tests in arbitrarily big thread pools with various policies available (all methods in their own thread, one thread per test class, etc...).
  3. Test that your code is multithread safe.
  4. Flexible test configuration.
  5. Support for data-driven testing (with @DataProvider).
  6. Support for parameters.
  7. Powerful execution model (no more TestSuite).
  8. Supported by a variety of tools and plug-ins (Eclipse, IDEA, Maven, etc...).
  9. Embeds BeanShell for further flexibility.
  10. Default JDK functions for runtime and logging (no dependencies).
  11. Dependent methods for application server testing.

TestNG is designed to cover all categories of tests: unit, functional, end-to-end, integration, etc...

Installation and Setup

TestNG dependency to maven pom.xml

<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.12</version>
<scope>test</scope>
</dependency>
TestNG Hello World Example

Writing and executing a simple TestNG program is mainly 3 step process.

  1. Code - write business logic of your test and annotate it with TestNG annotations
  2. Configure - add information on your test in testing.xml or in build.xml
  3. Run TestNG - it can be invoked from command line, ANT, IDE like Eclipse, IntelliJ's IDE

A Brief explanation of example (what needs to be tested):

We have a RandomNumberGenerator class which has a method generateFourDigitPin that generates a 4 digit PIN and returns as int. So here we want to test whether that random number is if of 4 digits or not. Below is the code:

Class to be tested:

packageexample.helloworld;
public class RandomNumberGenerator 
{
      publicintgenerateFourDigitPin()
      {
         return (int)(Math.random() * 10000);
      }
}

The TestNG test class:

packageexample.helloworld;

importorg.testng.Assert;
importorg.testng.annotations.AfterClass;
importorg.testng.annotations.BeforeClass;
importorg.testng.annotations.Test;

public class TestRandomNumberGenerator 
{
    RandomNumberGeneratorrng = null;

   @BeforeClass
   public void deSetup()
   {
          rng = new RandomNumberGenerator();
   }

  @Test
   public void testGenerateFourDigitPin()
   {
       intrandomNumber = rng.generateFourDigitPin();
       Assert.assertEquals(4, String.valueOf(randomNumber).length());
   }

    @AfterClass
     public void doCleanup()
     {
          //cleanup stuff goes here
     }
}

Ther testing.xml: