TestNG
Understanding TestNG & it's different features
.
.
TestNG (Test Next Generation) is a testing framework
🌟 Installation and Setup:
Maven Dependency (if using Maven):
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.X</version>
</dependency>
🌟 Create a TestNG XML File:
TestNG tests are often configured using an XML file. Create a file named testng.xml to define test
suites, test classes, and other configurations
<suite name="MyTestSuite">
<test name="MyTestClass">
<classes>
<class name="com.example.MyTestClass"/>
</classes>
</test>
</suite>
🌟 Test Annotations:
TestNG uses annotations to identify methods as test methods. Common annotations
include:@Test: Marks a method as a test method.
@BeforeSuite, @AfterSuite: Executed before/after the entire test suite.
@BeforeTest, @AfterTest: Executed before/after each test.
@BeforeClass, @AfterClass: Executed before/after each test class.
@BeforeMethod, @AfterMethod: Executed before/after each test method
🌟 Test Methods:
Write test methods and annotate them with @Test. Define assertions using TestNG assertion
methods (e.g., assertEquals, assertTrue).
public class MyTestClass {
@Test
public void testAddition() {
int result = 2 + 2;
Assert.assertEquals(result, 4, "Addition is incorrect");
}
}
🌟 Test Suites:
Group tests into suites using the testng.xml file. Define dependencies between test methods or
groups.
🌟 Parameterized Tests:
Use @Parameters annotation to pass parameters to test methods
@Test
@Parameters({"param1", "param2"})
public void testWithParameters(int param1, String param2) {
// Test logic using parameters
}
🌟 DataProvider:
Use @DataProvider to supply data to test methods
@DataProvider(name = "testData")
public Object[][] provideTestData() {
return new Object[][]{
{1, "apple"},
{2, "banana"},
{3, "cherry"}
};
}
@Test(dataProvider = "testData")
public void testWithData(int id, String name)..
🌟 Groups and Dependencies:
Group tests using the groups attribute and define dependencies between groups
@Test(groups = "smoke")
..
@Test(groups = "regression", dependsOnGroups = "smoke")
..
🌟 Listeners:
Implement TestNG listeners for custom actions before/after test methods, classes, suites, etc.
public class MyListener implements ITestListener ..
🌟 Parallel Execution:
TestNG supports parallel execution. Set parallel mode and thread count in the testng.xml file.
<suite name="MyTestSuite" parallel="tests" thread-count="5">
<!-- Test configurations -->
</suite>