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
- Annotations: Provides annotations like
@Test
,@BeforeSuite
,@AfterSuite
, etc., which offer fine-grained control over test execution. - Parallel Testing: Supports parallel execution of tests, which improves testing efficiency for large test suites.
- Data-Driven Testing: Supports data providers (
@DataProvider
) to enable parameterized testing. - Flexible Test Configuration: Allows configuration of test methods, suites, and dependencies through XML files or annotations.
- Dependent Methods: Supports test method dependencies using
dependsOnMethods
anddependsOnGroups
. - Customizable Test Execution: Allows grouping of tests and filtering tests to run specific subsets of the suite.
- Assertions: Includes assertions for verifying test conditions (
Assert.assertTrue
,Assert.assertEquals
, etc.). - Test Reporting: Generates detailed HTML and XML reports for executed tests.
- Integration: Works seamlessly with build tools like Maven, Gradle, and CI/CD tools like Jenkins.
- Multi-Threading: Facilitates running multiple tests in separate threads.
Common Annotations in TestNG
@Test
: Marks a method as a test case.@BeforeSuite
/@AfterSuite
: Executes methods before or after all tests in a suite.@BeforeTest
/@AfterTest
: Runs before or after the test tag in XML.@BeforeClass
/@AfterClass
: Executes methods before or after any method in the current class.@BeforeMethod
/@AfterMethod
: Runs before or after each test method.@DataProvider
: Supplies data for data-driven tests.
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
- Improved configuration and control compared to JUnit.
- Better support for test grouping and parallel execution.
- Enhanced reporting capabilities.
- Built-in support for parameterized tests without external libraries.
Common Use Cases
- Unit testing for Java applications.
- Integration and functional testing.
- Automated regression testing.
- Parallel testing to speed up execution.