Thursday, 14 June 2018

TestNG Grouping and Depends On

In our previous post we have learnt about TestNG annotations . In this post we will see how we can group test cases and specify dependent test cases using TestNG annotations.

Groups‘ is one annotation of TestNG which can be used in the execution of multiple tests as a group. Let’s say you have hundred tests of class Devices and in it ten methods of laptops, ten method of Notebooks and so on. You probably like to run all the Notebooks tests together in a batch. And you want all to be in a single test suite. With the help of grouping you can efficiently address this situation.

How to do it…
1) Create two methods for Laptops, two methods for Notebooks and one method in conjunction with Laptops and Notebooks.
2) Group them separately with using  (groups = { ” Group Name” })

import org.testng.annotations.Test;
public class TestGrouping {
  @Test (groups = { "Laptops" })
  public void Car1() {
   System.out.println("Batch Laptops- Test Laptops1");
  @Test (groups = { "Laptops" })
  public void Car2() {
   System.out.println("Batch Laptops- Test Laptops 2");
  @Test (groups = { "Notebooks" })
  public void Scooter1() {
   System.out.println("Batch Notebooks- Test Notebooks 1");
  @Test (groups = { "Notebooks" })
  public void Scooter2() {
   System.out.println("Batch Notebooks- Test Notebooks2");
  @Test (groups = { "Laptops", "Touch Screen Laptops" })
  public void Sedan1() {
   System.out.println("Batch Touch Screen Laptops- Test Touch Screen Laptops1");

Add below code into TestNG.xml-

<suite name="Suite">
    <test name="Practice Grouping">
  <include name="Laptops" />
     <class name="PackageName.TestGrouping" />

Run The TestNG,xml -> right click -> Run as -> TestNG Suit.

Dependenct Test -

you may need to invoke methods in a Test case in a particular order or you want to share some data and state between methods. This kind of dependency is supported by TestNG .
TestNG allows you to specify dependencies with two options given below.
  • Using attributes dependsOnMethods in @Test annotations
  • Using attributes dependsOnGroups in @Test annotations.

mport org.testng.annotations.Test;
public class Dependent {
  @Test (dependsOnMethods = { "OpenBrowser" })
  public void SignIn() {
   System.out.println("This will execute SignIn");
  public void OpenBrowser() {
   System.out.println("This will execute Open Browser");
  @Test (dependsOnMethods = { "SignIn" })
  public void SignOut() {
   System.out.println("This will execute Log Out");

In case of any feedback and questions post in the comment section below.


Post a Comment