How to create test dependencies in Selenium using TestNG?

When we perform software testing then we come across many scenarios in which one test case depends on another test case. Suppose if the independent test case fails then the test case which is dependent will be skipped or failed due to the failure of the independent test case. This is one of the features of the TestNG which gives flexibility to automation engineers to define the test dependencies.

First time I used this technique in my testing project when two new functional stories came. The first story was the new functionality which is the configuration of some settings in SAP Hybris Management Console (HMC) and we had to validate the changes in webshop portal. This webshop validation story came later, hence, the later story was the dependent story on the former story which sets the configuration in SAP HMC. I used the technique of creating test dependencies through the grouping of the test cases, so I simply put group dependencies of the tests.

I would like to recommend you some of the TestNG tutorials which will help you design your tests in Selenium in an effective manner:

These tutorials will help you if you want to broaden your knowledge of the TestNG. Now let’s have a look at the implementation part of the techniques to create test dependencies in the Selenium project using the TestNG framework.

Definition of test dependencies technique

You have two choices to create the definition of test dependencies. Let’s look at them:

Definition# 1: By using dependsOnMethods

In this technique, we will simply add dependsOnMethods beside the @Test annotation with the method name at which the context test will depend. Let’s say, a test method name, dependentTest depends on any independent test whose name is independentTest. Here is the definition:

Here is the sample program:

In this program, testMethod1() depends on testMethod2(). So testMethod1 will be executed when the testMethod2 successfully gets executed. Look at its console output. We see that the print statement which is written inside testMethod2 gets executed first then testMethod1 came in the picture.

test dependencies by method

Definition# 2: By using groups declaration through testng.xml

In this technique, we put each test in the group. We have already discussed the technique to group tests in Selenium in our previous tutorial. So once grouping of tests is done, then we will create dependencies in testng.xml. Here is the sample definition:

Below is the sample program which uses test groups to create dependencies.


testng.xml file

When test suit ran, the first independent test gets invoked then dependent tests come in to run the state. See console output below.

test dependences by groups

That’s all about creating test dependencies in Selenium using TestNG. You can post your queries below in the comment and also you can join our Facebook group for more updates.

Join Inviul fb group

Leave a Reply