Saturday, November 5, 2016

Using dependencies and priority in TestNG tests: Ordering tests execution

Suppose there are three tests in a test class which needs to be executed, we can define the tests in the class as shown below:


public class TestOrder {
@Test
public void TestA() {
System.out.println("test a");
}

@Test
public void TestB() {
System.out.println("test b");
}

@Test
public void TestC() {
System.out.println("test c");
}
}


When we execute the test class, all the three tests are executed, but order of the test is not sure. We can prioritize the test using priority.


public class TestOrder {
@Test(priority=1)
public void TestA() {
System.out.println("test a");
}

@Test(priority=2)
public void TestB() {
System.out.println("test b");
}

@Test(priority=3)
public void TestC() {
System.out.println("test c");
}
}


Since there can be many tests in a test suite, and it can be difficult to prioritize tests based on numbering tests. In such cases,we can prioritize the tests based on dependsongroup or dependsonmethod as shown below.  Using groups, we can group the tests based on functionality and scope of the tests




public class TestOrder {
@Test(groups = { "smoke" })
public void TestA() {
System.out.println("test a");
}

@Test(dependsOnMethods = { "TestD" }, groups = { "regression" })
public void TestB() {
System.out.println("test b");
}

@Test(dependsOnGroups = { "smoke" })
public void TestC() {
System.out.println("test c");
}

@Test
public void TestD() {
System.out.println("test d");
}
}

No comments:

Post a Comment