Essential TestNG Annotations and Techniques


If you're diving into the world of TestNG for Java testing, understanding its annotations is essential. These annotations are the backbone of creating robust and maintainable test suites. This guide will walk you through the most important annotations, how to organize your tests, and how to handle advanced concepts like parameterization and assertions. Let's get started!
Important Annotations in TestNG
Core Annotations
@Test: Marks a method as a test method.
@BeforeMethod: Executes before each test method.
@AfterMethod: Executes after each test method.
@BeforeClass: Executes once before the first method in the current class is invoked.
@AfterClass: Executes once after all the methods in the current class have been run.
@BeforeTest: Executes before any test method that belongs to the classes inside the <test> tag is run.
@AfterTest: Executes after all the test methods that belong to the classes inside the <test> tag have run.
@BeforeSuite: Executes before all tests in this suite.
@AfterSuite: Executes after all tests in this suite have run.
Parameterization and Data Handling
@Parameters: Passes parameters to test methods from the TestNG XML configuration file.
@Optional: Specifies optional parameters with default values.
@DataProvider: Supplies data to a test method. It allows you to run the test multiple times with different data sets.
Example Usage
javaCopy codeimport org.testng.annotations.*;
public class TestNGExample {
@BeforeSuite
public void beforeSuite() {
System.out.println("Before Suite");
}
@AfterSuite
public void afterSuite() {
System.out.println("After Suite");
}
@BeforeClass
public void beforeClass() {
System.out.println("Before Class");
}
@AfterClass
public void afterClass() {
System.out.println("After Class");
}
@BeforeMethod
public void beforeMethod() {
System.out.println("Before Method");
}
@AfterMethod
public void afterMethod() {
System.out.println("After Method");
}
@Test
public void testMethod1() {
System.out.println("Test Method 1");
}
@Test
public void testMethod2() {
System.out.println("Test Method 2");
}
}
Organizing Tests
Multiple Test Methods in the Same Class
Yes, you can include multiple test methods in the same TestNG class. This allows you to group related tests together, making your test suite more organized and easier to manage.
Default Order of Execution
By default, TestNG executes test methods in alphabetical order. This can be useful, but often you'll need a specific execution order.
Controlling Execution Order
To execute test methods in a required order, you use the priority
attribute. The lower the priority value, the earlier the method will run.
javaCopy code@Test(priority = 1)
public void firstTest() {
System.out.println("First Test");
}
@Test(priority = 2)
public void secondTest() {
System.out.println("Second Test");
}
Default priority is 0.
You can use negative numbers.
Decimal numbers and variables are not allowed.
If two methods have the same priority, they are executed in alphabetical order.
TestNG executes methods in ascending order of the priority value.
Executing a Test Method Multiple Times
Use the invocationCount
attribute to run a test method multiple times.
javaCopy code@Test(invocationCount = 3)
public void repeatedTest() {
System.out.println("This test runs three times");
}
Default
invocationCount
is 1.If set to 0 or a negative value, the method will not execute.
Decimal numbers and variables are not allowed.
Data Providers
Data providers allow you to run tests multiple times with different data. This is essential for data-driven testing.
javaCopy code@DataProvider(name = "userData")
public Object[][] getData() {
return new Object[][] {
{"UserA", 123},
{"UserB", 456}
};
}
@Test(dataProvider = "userData")
public void createUser(String username, int password) {
System.out.println("Create user: " + username + " with password: " + password);
}
If you encounter the error java.lang.NoClassDefFoundError: com/google/common/primitives/Ints
, download the necessary jar file here and add it to your build path.
TestNG Groups
Groups allow you to categorize tests and run specific sets of tests.
javaCopy code@Test(groups = {"user", "smoke"})
public void createUser() {
System.out.println("Create User");
}
@Test(groups = {"user"})
public void deleteUser() {
System.out.println("Delete User");
}
@Test(groups = {"product", "smoke"})
public void createProduct() {
System.out.println("Create Product");
}
Assertions
Assertions are used to validate test results. TestNG provides two types of assertions: Assert
and SoftAssert
.
Hard Assert
A hard assert will stop execution upon failure.
javaCopy codeAssert.assertEquals(actualTitle, expectedTitle);
Soft Assert
A soft assert allows the test to continue even if an assertion fails.
javaCopy codeSoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(actualTitle, expectedTitle);
softAssert.assertAll(); // This must be called at the end
Difference Between Assert and SoftAssert
Assert | SoftAssert |
All methods are static | All methods are non-static |
Stops execution on failure | Continues execution on failure |
No need to call assertAll() | Must call assertAll() |
TestNG Parameters
You can pass parameters from the TestNG XML configuration file to your test methods.
xmlCopy code<test name="Test Parameters">
<parameter name="city" value="New York"/>
<parameter name="area" value="Manhattan"/>
<classes>
<class name="Param.DemoA"/>
</classes>
</test>
javaCopy code@Parameters({"city", "area"})
@Test
public void testA(@Optional("Delhi") String city, String area) {
System.out.println("City: " + city + ", Area: " + area);
}
Conclusion
TestNG annotations provide a powerful way to control the flow and structure of your test suite. Understanding how to use these annotations effectively can greatly enhance your testing capabilities. Whether you're organizing tests, handling data, or managing assertions, TestNG offers the tools you need to create efficient and reliable tests. Happy testing!
Subscribe to my newsletter
Read articles from priya ramteke directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
