TestNG Tutorials 60: Dependency in TestNG – Creating Dependency Among Test Methods – DependsOnMethod

We are going to see another important concept or feature provided by TestNG. This feature is called as Dependency.

Suppose, we need to post a status on Facebook. Let’s write a Test Case for it:

Step 1: Launch browser.

Step 2: Launch Facebook url.

Step 3: Create an account on Facebook.

Step 4: Post a status.

In above test case, Step 4 is what matters. But to get Step 4 to execute, we have three pre steps which need to be executed first in order. Step 1 is not an actual part of functionality testing. It provides a platform to test functionality. So we can keep Step 1 in @Before annotated steps. But Step 2, Step 3 and Step 4 are part of Test. We should keep them under @Test annotation. So Step 2 and Step 3 must be executed first before Step 4. We can achieve this using “priority” concept of TestNG.

There is another way of achieving this as well which is called Dependency. TestNG provides an attribute named “dependsOnMethods”. Using this attribute we can mention a method name or a list of methods with @Test annotation, on which your test method is dependent.

In above test case, Step 4 is dependent on Step 2 and Step 3. Step 2 should execute first followed by Step 3 and then Step 4. If we mention all dependent method names in Step 4, TestNG cannot guarantee of execution of Step 2 and Step 3 in order. So we will use multilevel dependency here.

An example is below:

package Dependecy;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class MultiLevelDependency {
	public void launchBrowser()
		System.out.println("browser Launched.");
	public void loadFacebookURL()
		System.out.println("Facebook URL loaded.");
	 * registerOnFacebook depends  on loadFacebookURL
	@Test(dependsOnMethods = {"loadFacebookURL"})
	public void registerOnFacebook()
		System.out.println("Register on Facebook.");
	 * postStatusOnFacebook depends on registerOnFacebook
	@Test(dependsOnMethods = {"registerOnFacebook"})
	public void postStatusOnFacebook()
		System.out.println("Post an status on Facebook.");


[RemoteTestNG] detected TestNG version 6.14.2
browser Launched.
Facebook URL loaded.
Register on Facebook.
Post an status on Facebook.
PASSED: loadFacebookURL
PASSED: registerOnFacebook
PASSED: postStatusOnFacebook

Default test
Tests run: 3, Failures: 0, Skips: 0

Default suite
Total tests run: 3, Failures: 0, Skips: 0


You can see that using multilevel dependency we created linear dependency and executed test in a order. We will see more concept in Dependency.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.

Leave a Reply

Your email address will not be published. Required fields are marked *