Sunday, 24 March 2013

Java TestNG Example

This post illustrates some of the feature of TestNG. The code example is available at GitHub in the Java-TestNG directory. We use maven. Therefore, the configuration will located in the pom.xml.

Source Code

We use a very simple class returning integers for testing purposes:
public class Generate {

    private Generate() { }

    public static int aOne() {
        return 1;

    public static int aTwo() {
        return 2;



Test Code

The test code for the above class is the following:
public class GenerateNGTest {

    public GenerateNGTest() { }

    @Test(groups = {"testGroupA"})
    public void testAOne() {

    @Test(groups = {"testGroupA", "testGroupB", "windows.QTests"})
    public void testATwo() {

    @Test(groups = {"testGroupA", "testGroupC", "windows.PTests"})
    public void testAThree() {

    @Parameters({ "testNgParam" })
    @Test(groups = {"testGroupA"})
    public void testAFour(@Optional("4") String testNgParam) {

    @Parameters({ "testNgParam2" })
    @Test(groups = {"testGroupA"})
    public void testASix(String testNgParam2) {

    public class DataForTests {

        @DataProvider(name = "forTestAFive")
        public Object[][] forTestAFive() {
            return new Object[][] {
                { new Integer(5) },
                { new Integer(6) }


    @Test(dataProvider = "forTestAFive", dataProviderClass = DataForTests.class)
    public void testAFive(int param) {

    @Test(dependsOnGroups = { "windows.*" })
    public void testASeven() {

  • Some test groups are defined for test methods. These can be activated in the configuration described further.
  • The testAFour() method takes in a parameter and defaults to 4 if none is provided.
  • Rather than setting parameters in the configuration, one can define a DataForTests class and use it to pass parameters as in the testAFive() method.
In this example, we do not cover factories and automatic test generation, programmatic executions of tests and test methods interceptors.    


In the pom.xml:
We activate tests belonging to testGroupA and we pass parameter values for testNgParam and testNgParam2. We also let TestNG run each test method in parallel using 2 threads. This can significantly accelerate the testing phase when compiling the project.

No comments:

Post a comment