How To Group And Run Selenium Test Cases Using Testng

Grouping tests Is another very good feature of testng using which you can create group of test methods. You can create a group of test methods based on functionality and features, or based on modules or based on testing types like functional testing, sanity testing etc.. This way you can differentiate specific group test methods from all test methods.

Benefits of grouping
Supposing you have 20 different test methods In single test case and from them you wants to run only those test methods which are related to checking E-Mail. You can do It very easily using testng grouping feature as bellow example.

Create bellow given class file under your project In eclipse
package Testing_Pack;

import org.testng.annotations.Test;

public class Grouping {
 //"check-mail" group test method.
 @Test(groups={"check-mail"}, priority =0)
 public void logIn(){
 System.out.println("Log In.");
 //Do not have any group.
 public void viewNews(){
 System.out.println("Viewing News.");
 //"check-mail" group test method.
 @Test(groups={"check-mail"}, priority =1)
 public void checkMail(){
 System.out.println("Checking Mail.");
 //"check-mail" group test method.
 @Test(groups={"check-mail"}, priority =2)
 public void logOut(){

In above example, You can see that @Test methods logIn(), checkMail() and logOut() has groups attribute with same value "check-mail". That means all these three @Test methods are of same group. Now If I wants to execute only "check-mail" group @Test methods then I have to configure my testng.xml file as bellow.

<!DOCTYPE suite SYSTEM "" >
<suite name="Group Test Suite" verbose="1">
  <test name="Group Test" >
   <include name="check-mail" />
  <class name="Testing_Pack.Grouping" />

In above xml file, I have used two new tags. <groups> and <run>.  <groups> tag defines the group and </run> tag represents the group that needs to be run. include tag describes which group needs to be executed. Above xml will only execute those test methods which are available In class = Testing_Pack.Grouping and @Test methods which have group name="check-mail". That means only logIn(), checkMail() and logOut() will be executed and viewNews() method will be not executed.


Execution result will looks like bellow.
This way, Testng grouping feature can help you to execute only specific group tests.

1 comment:

  1. Hi,

    Which one is better way to write scripts in Selenium ?
    either 1. Writing scripts in single class file with several test methods or 2. Writing scripts in multiple class files.

    Or either way is good here while using testNG framework to run scripts.