In TestNG, you can create test dependencies to ensure that a particular test method runs only if the method it depends on completes successfully. This is especially useful when a certain test method needs another method to be successful before it can be meaningfully executed.
Here’s how you can define test dependencies in TestNG:
Using dependsOnMethods
You can specify that one test method depends on a single method or multiple methods using the dependsOnMethods attribute.
import org.testng.annotations.Test;
public class TestNGDependenciesExample {
@Test
public void signIn() {
System.out.println("Signing in");
// Assuming the login is successful.
}
@Test(dependsOnMethods = {"signIn"})
public void openDashboard() {
System.out.println("Opening dashboard");
// Operations after signing in.
}
@Test(dependsOnMethods = {"signIn", "openDashboard"})
public void performSomeTask() {
System.out.println("Performing some task on the dashboard");
// Operations on the dashboard.
}
}
Here:
openDashboardwill only run ifsignInsucceeds.performSomeTaskwill only run if bothsignInandopenDashboardsucceed.
Using dependsOnGroups
You can also specify that test methods depend on groups instead of specific methods. This is helpful when you want to create a logical group of methods and have dependencies based on these groups.
import org.testng.annotations.Test;
public class TestNGGroupDependenciesExample {
@Test(groups = {"signIn"})
public void signInMethod1() {
System.out.println("Signing in - Method 1");
}
@Test(groups = {"signIn"})
public void signInMethod2() {
System.out.println("Signing in - Method 2");
}
@Test(groups = {"dashboard"}, dependsOnGroups = {"signIn"})
public void openDashboard() {
System.out.println("Opening dashboard");
}
}
Here:
signInMethod1andsignInMethod2are part of thesignIngroup.openDashboardis part of thedashboardgroup and will only run if all methods in thesignIngroup succeed.