TestNG Tutorial and Example – Dependency Test

Dependency is common need in unit testing, because the test cases may share some state, data and conditions, in order to write repeatable cases and run them in isolation, TestNG supports the declaration of explicit dependencies between test methods, it is enabled with two attributes of the @Test annotation, dependsOnGroups and dependsOnMethods.

Testing case depends on the methods

The following example demos that testmethod is declared as depending on method initEnvironmentTest(), which guarantees that initEnvironmentTest() will always be invoked first. If case initEnvironmentTest is fail, testmethod will be skipped.

TestNGDependencyTest.java
import org.testng.annotations.*;

/**
 * TestNG Dependency Test
 * @author asjava.com
 *
 */
public class TestNGDependencyTest {

	@Test
	public void initEnvironmentTest() {
	   System.out.println("This is initEnvironmentTest");
	}

	@Test(dependsOnMethods={"initEnvironmentTest"})
	public void testmethod() {
		System.out.println("This is testmethod");
	}
}

However, If you want even initEnvironmentTest is fail but still run testmethod, you can add the attribute alwaysRun=false to @Test annotation.

Testing case depends on the group.

The following example demos that testmethod is declared as depending on group init which have two methods initEnvironmentTest1 and initEnvironmentTest2, so the two methods will always invoked first, note the order of invocation for the two methods that belong in group init is not guaranteed.

TestNGDependencyTest.java
import org.testng.annotations.*;

/**
 * TestNG Dependency Test
 * @author asjava.com
 *
 */
public class TestNGDependencyTest {

	@Test(groups = { "init" })
	public void initEnvironmentTest1() {
	     System.out.println("This is initEnvironmentTest1");
	}

        @Test(groups = { "init" })
        public void initEnvironmentTest2() {
             System.out.println("This is initEnvironmentTest2");
        }

	@Test(dependsOnGroups={"init"})
	public void testmethod() {
             System.out.println("This is testmethod");
	}
}

Оцените статью
ASJAVA.COM
Добавить комментарий

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

*

code

  1. praveen

    How can I share data between two test methods using testng Dependency Test.means how the return value of one method is available to dependant method

    Ответить