TestNG dependencies, types of dependencies and it’s details are explained in this post.
Why we use dependencies:
- To run a test method before invoking another test methods
- To share some data and states between test methods
TestNG dependency is used at @Test annotation, it allows a test method to depend on either another test method or a group.
- dependsOnMethods is used in @Test annotation to depend on a method.
- dependsOnGroups is used in @Test annotation to depend on a group.
Dependency on methods:
Above test method test1() is declared as dependent on test method connectionToDB(), hence connectionToDB() will always be executed first.
Dependency on Groups:
In the above example test method test2() is declared on group init, hence test methods serverStarted() and initEnvironment() will always be executed first.
TestNG support two types of DEPENDENCIES:
- Hard dependency:
- The test method will not be invoked and marked as skip in report if any dependency methods failed,
- By default, hard dependency is enabled ( alwaysRun=false)
- Soft dependency:
- The main test methods will be invoked if any dependency method fails.
- To enable this, add “alwaysRun=true” in @Test annotation
Note: A method can be dependent on multiple other test methods, use dependentOnMethods with “,” separator in @Test annotation.
Below is the complete code of TestNG class with dependency methods and groups.
- In the above example, here are the dependencies.
- method test1() is dependent on connectToDB() methods
- method test2() is dependent on group init
- method test3() is dependent on method failedTest()
testng.xml file (dependent.xml)
Following is the output When executed the above dependent.xml file.
- method test1() dependent on connectToDB() methods, hence connectToDB method was executed before method test1()
- method test2() dependent on group init, hence methods serverStarted() and initEnvironment() were executed before method test2()
- method test3() dependent on method failedTest(), this failedTest() method were failed due to Assert, hence method test3() was skipped.
In this post, we learned TestNG method dependency on other methods and method dependency on Groups.