TestNG is testing framework in Java inspired by the JUnit test framework. TestNG has capabilities far greater than what JUnit provides. While JUnit was primarily designed for unit testing of the code, TestNG framework allows the users to write test ranging from unit tests to integration tests.
Getting Started
The best way to learn how things work in java is to avoid using the IDE. Having the knowledge on how things work will enrich the IDE experience. In this blog I will try to understand TestNG from command line.
Configuring TestNG is simple. Download the latest version of TestNG archive from TestNG site. Unzip the file and place the tesng-X.Y.Z.jar such that it is visible in CLASSPATH. I usually have all my third party jars placed under ‘third_party’ directory. Here I’ll place the jar file as ‘third_party/testng/X.Y.Z/testng.jar’ [yes I renamed testng-X.Y.Z.jar to testng.jar].
Writing a testng test
Any Java class annotated with the TestNG annotations can be treated as TestNG testcase. You can get the list of TestNG annotations here. Here is a simple Java code to return sum of two numbers
package com.istack.java.example; public class Sum { private int a; private int b; public Sum(int a, int b) { this.a = a; this.b = b; } public int calculate() { return this.a + this.b; } }
TestNG test case
package com.istack.java.example; import org.testng.annotations.*; import org.testng.Assert; public class TestSum { /*@Test*/ public void testSum() { Sum sum = new Sum(4,1); Assert.assertEquals(sum.calc(), 5); } }
Executing in TestNG
To execute a testng test from command line, the testng.xml need to be created. Below is the testng.xml file for the Test code
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name="Suite1" verbose="1"> <test name="TestSunFor5"> <classes> <class name="com.istack.java.example.TestSum" /> </classes> </test> </suite>
Below command is executed to run the test (given everything is in classpath)
java org.testng.TestNG testng1.xml
NOTE: You must compile the java files and make sure that these files and the testng.jar are in classpath
Results
Output of the above command would be like below :
[TestNG] Running: C:\Documents and Settings\skgupta\My Documents\JavaExamples\testng\testng.xml Everything is wwll.. Lets learn more TestNG =============================================== Suite1 Total tests run: 1, Failures: 0, Skips: 0 ===============================================
TestNG will generate result in ‘test-output’ directory
References: http://www.testng.org/