Grouping and Dependent Test case

Test Case Grouping:

Grouping is one of the important features of TestNG, which doesn’t exist in the JUnit framework. We can execute those methods that belong to a single group.

Groups are declared in testng.xml file using the tag. We can use it either under the or tag. Groups specified in the tag apply to all the tags under it.

Let us see an example:

package testFramework;

import org.testng.annotations.Test;

public class GroupTests {

  @Test(groups = {"Sanity"})
  public void test1() {
    System.out.println("This is sanity test case 1");
  }
  
  @Test(groups = {"Sanity"})
  public void test2() {
    System.out.println("This is sanity test case 2");
  }

  @Test(groups = {"Sanity"})
  public void test3() {
    System.out.println("This is sanity test case 3");
  }
  
  @Test(groups = {"Acceptance"})
  public void test4() {
    System.out.println("This is Acceptance test case 4");
  }
  
  @Test(groups = {"Acceptance"})
  public void test5() {
    System.out.println("This is Acceptance test case 5");
  }
}

 

Create a testng.xml file.
testng-xml

Execute the test by right click on testng.xml file and select Run As > TestNG Suite.

TestNG-suite

In this example, we call the group name as ‘Sanity’ in testng.xml file so it is executed only those test cases whose group name as ‘Sanity’. We can also execute multiple groups altogether.

Let us see an example:

sanity-group

Dependent Test Case:

There might be a chance to invoke methods in a test case in a particular order. This kind of dependency is supported by TestNG as it supports the declaration of explicit dependencies between test methods.

TestNG allows you to specify dependencies using dependsOnMethods or dependsOnGroups in @Test annotations

Let us see an example:

package testFramework;

import org.testng.annotations.Test;

public class GroupTests {

  @Test(dependsOnMethods = {"LoginPage"})
  public void OpenApp() {
    System.out.println("This is Application page");
  }

  @Test(groups = {"Sanity"})
  public void LoginPage() {
    System.out.println("This is Login page");
  }

}

 

Group-output

group-result