What Are Dependent Tests in TestNG?
TestNG allows you to create test dependencies, meaning you can specify that:
A test method depends on another method or group
If the depended method fails, is skipped, or is not run, the dependent method will also be skipped
Types of Dependencies in TestNG
Type | Annotation Attribute | Description |
---|---|---|
Method Dependency | dependsOnMethods | Test method runs only if other method(s) pass |
Group Dependency | dependsOnGroups | Test method runs only if group(s) pass |
If a test case execution depends upon successful execution of other test cases, then in this condition we can use attribute 'dependsOnMethods' in @Test annotation.
Example Java Code for method dependency
import org.testng.annotations.Test; public class DependentTestExample { @Test public void launchApp() { System.out.println("App launched successfully."); } @Test(dependsOnMethods = "launchApp") public void login() { System.out.println("Logged in successfully."); } @Test(dependsOnMethods = {"login"}) public void searchProduct() { System.out.println("Product searched successfully."); } @Test(dependsOnMethods = {"searchProduct"}) public void logout() { System.out.println("Logged out successfully."); } }
Output
App launched successfully. Logged in successfully. Product searched successfully. Logged out successfully.
Note: If a Test Fails then searchProduct() and logout() will be skipped.
Example Java Code for group dependency
import org.testng.annotations.Test; public class GroupDependencyExample { @Test(groups = "database") public void connectToDB() { System.out.println("✔ Database connected."); } @Test(groups = "database") public void fetchData() { System.out.println("✔ Data fetched from DB."); } @Test(dependsOnGroups = "database") public void generateReport() { System.out.println("✔ Report generated using DB data."); } }
Optional Attributes
Attribute | Description |
---|---|
alwaysRun = true | Run test even if dependency fails |
enabled = false | Disable the test |
dependsOnMethods | Declare method dependencies |
dependsOnGroups | Declare group dependencies |
Example of attribute:
alwaysRun
@Test(dependsOnMethods = "login", alwaysRun = true) public void sendEmail() { System.out.println("Email sent (even if login fails)."); }
No comments:
Post a Comment