First TestNG test

Write TestNG test

Writing tests using TestNG is easy. There are only 2 steps:

  1. Add @Test annotation to your methods so that TestNG can recognize that the methods are in fact test methods.
  2. In your test methods, use TestNG's assertion methods(e.g. assertEquals(), assertTrue(), assertNotNull(), etc) to validate the expected results.

The code below demontrates how to use TestNG to verify the correctness of the methods. In this case, it will check whether add() method is correctly returning the sum of 2 integers. There are 2 test methods implemented below. The first test method, testAddPositive(), checks whether it correctly adds 2 positive values. The second test method, testAddNegative(), checks whether it correctly adds 2 negative values. Obviously, you can continue to add as much test methods with different test cases as you want.

/**
 * AddTest.java
 * Show how to use TestNG.
 * @author Xuan Ngo
 */
 
import org.testng.annotations.Test;           // Import @Test annotattion.
import static org.testng.Assert.assertEquals; // Import assertEquals() method.
 
public class AddTest
{
  @Test(description="Testing add() method with positive values.")
  public void testAddPositive()
  {
    int iActual = this.add(2, 3);
    int iExpected = 5;
    assertEquals(iActual, iExpected, "add() doesn't return expected positive value.");
  }
 
  @Test(description="Testing add() method with negative values.")
  public void testAddNegative()
  {
    int iActual = this.add(-2, -3);
    int iExpected = -5;
    assertEquals(iActual, iExpected, "add() doesn't return expected negative value.");
  }
 
  /**
   * I put the implementation of add() here so that the whole test class is self-complete.
   * In real life, this method should come from another class so that there is 
   * a complete separation between the test class and the actual class.
   */
  public int add(int a, int b)
  {
    return a+b;
  }
}

Compile TestNG test class

Execute the following command to compile code above. Note: Change the paths according to the locations of your files.

javac -classpath c:\testng-5.8-jdk15.jar AddTest.java

Execute TestNG test class

Execute the following command to run test. Note: Change the paths according to the locations of your files.

java -classpath c:\testng-5.8-jdk15.jar;. org.testng.TestNG -testclass AddTest

TestNG's results

The result on the Command Prompt will look like the following:

[Parser] Running:
  Command line suite
===============================================
Command line suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

The result shows that there were 2 tests ran: 0 test failed and 0 test skipped. Therefore, all tests were ran successfully. By default, a detailed report will be created by TestNG in test-output/ directory. Open test-output/index.html with your browser to see the complete report.