TestNG: Dependent Testing

Profile picture for user devraj

Sometime you may want data to be shared between methods or invoke method in particular order.

For example you may want that certain number of test cases completed or succeeded before running more methods or to initialize your tests while wanting this initialization methods to be test methods as well. 

TestNG allows you to specify dependencies either with annotations or in XML.

Dependencies with Annotations

We can use the attributes dependsOnMethods or dependsOnGroups, found on the @Test annotation.

1. dependsOnMethods Attributes

There are 2 kinds of dependencies:

a. Hard Dependencies: All the dependencies method must run and successful to run a dependent method. If any of dependencies method failed the dependent method will not run and marked as skip.

b. Soft Dependencies:  Even if some of dependencies method failed the dependent method will execute. A soft dependency is obtained by adding "alwaysRun=true" in your @Test annotation.

2. dependsOnGroups Attributes

There can be a method which depend on entire group of methods.

Check below code to understand dependsOnMethods and dependsOnGroups

package learning.test.testng;

import org.testng.annotations.Test;

public class DependencyMethodTest 
{
 
	@Test(groups = { "smoke" })
	public void search() {
		System.out.println("Search Method Executed.");
	}
	 
	@Test(groups = { "smoke" })
	public void home() {
		System.out.println("Home Method Executed.");
	}
	 
	@Test(dependsOnGroups = { "smoke.*" })
	public void smokeTest() {
		System.out.print("Smoke Test Executed");
	}

	@Test
	public void regression() 
	{
		int a = 10/0;
		System.out.println("Regression Method Executed");
	}
	 
	@Test(dependsOnMethods = { "regression" })
	public void regressionNotOK() {
		System.out.println("This will not execute because regression method fail.");
	}
	
	@Test(dependsOnMethods = { "regression" }, alwaysRun=true)
	public void regressionOK() {
		System.out.println("This will execute even if regression method fail");
	}

}

After execution you will see that smokeTest method executed after home and search method because home and search were part of smoke group.

Also, regression method fail because of divide by zero error. regressionNotOK method not executed(skipped) because regression method failed. regressionOk method Pass even if regression method fail because alwaysRun was set true.

Dependencies in XML

Using dependency tag you can specify your group dependency in testng.xml file. Example

<test name="Regression Suite">
  <groups>
    <dependencies>
      <group name="smoke" depends-on="group1  group2" />
      <group name="regression" depends-on="group1 group2 group3" />
    </dependencies>
  </groups>
</test>

depent-on contains space separated name of groups.

Tags