Writing tests using TestNG is easy. There are only 2 steps:
The AddTest.java file found below is an example demonstrating 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. */ private int add(int a, int b) { return a+b; } }
Execute the following command to compile AddTest.java. Note: Change the paths according to the locations of your files.
javac -classpath c:\testng-5.8-jdk15.jar AddTest.javaExecute 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 AddTestThe 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 ===============================================
| Attachment | Size |
|---|---|
| AddTest.java | 1.07 KB |