Dung (Donny) Nguyen

Senior Software Engineer

TestNG

TestNG is a popular testing framework for Java, inspired by JUnit and NUnit, designed to provide powerful and flexible testing functionalities for developers. Its name stands for “Test Next Generation,” emphasizing its enhancements over older testing frameworks.

Key Features of TestNG

  1. Annotations: Provides annotations like @Test, @BeforeSuite, @AfterSuite, etc., which offer fine-grained control over test execution.
  2. Parallel Testing: Supports parallel execution of tests, which improves testing efficiency for large test suites.
  3. Data-Driven Testing: Supports data providers (@DataProvider) to enable parameterized testing.
  4. Flexible Test Configuration: Allows configuration of test methods, suites, and dependencies through XML files or annotations.
  5. Dependent Methods: Supports test method dependencies using dependsOnMethods and dependsOnGroups.
  6. Customizable Test Execution: Allows grouping of tests and filtering tests to run specific subsets of the suite.
  7. Assertions: Includes assertions for verifying test conditions (Assert.assertTrue, Assert.assertEquals, etc.).
  8. Test Reporting: Generates detailed HTML and XML reports for executed tests.
  9. Integration: Works seamlessly with build tools like Maven, Gradle, and CI/CD tools like Jenkins.
  10. Multi-Threading: Facilitates running multiple tests in separate threads.

Common Annotations in TestNG

Example Code

import org.testng.Assert;
import org.testng.annotations.*;

public class TestNGExample {
    @BeforeClass
    public void setup() {
        System.out.println("Setup before class");
    }

    @Test
    public void testAddition() {
        int result = 5 + 3;
        Assert.assertEquals(result, 8, "Addition test failed");
    }

    @Test(dataProvider = "dataMethod")
    public void testWithData(int input, int expected) {
        int result = input + 2;
        Assert.assertEquals(result, expected);
    }

    @DataProvider
    public Object[][] dataMethod() {
        return new Object[][]{ {1, 3}, {2, 4}, {3, 5} };
    }

    @AfterClass
    public void teardown() {
        System.out.println("Teardown after class");
    }
}

Advantages of TestNG

Common Use Cases