import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;

public class GroupsInTestNG {
    @BeforeGroups({“secondGroup”,”firstGroup”})
    public void executeBeforeGroup(){
        System.out.println(“executeBefore both Group”);
    }
    @AfterGroups(“firstGroup”)
    public void executeAfterGroup(){
        System.out.println(“executeAfter firstGroup”);
    }
    
    @Test(groups=”firstGroup”)
    public void method1(){
        System.out.println(“method1”);
    }
    @Test(groups=”firstGroup”)
    public void method2(){
        System.out.println(“method2”);
    }
    @Test(groups=”secondGroup”)
    public void method3(){
        System.out.println(“method3”);
    }
    @Test(groups=”secondGroup”)
    public void method4(){
        System.out.println(“method4”);
    }
    @Test(dependsOnGroups={“secondGroup”,”firstGroup”})
    public void method5(){
        System.out.println(“if both group passed then method5 test will execute”);
    }
}

testng.xml
————-

<suite name=”Suite” parallel=”none”>
  <test name=”Test1″>
    <classes>
      <class name=”advancedSelenium.GroupsInTestNG”/>
    </classes>
  </test> 
  <test name=”Test2″>
      <groups>
          <run>
          <include name=”secondGroup”></include>
          </run>
      </groups>
    <classes>
      <class name=”advancedSelenium.GroupsInTestNG”/>
    </classes>
  </test> 
</suite> 

Output
———-

executeBefore both Group
method1
method2
executeAfter firstGroup
executeBefore both Group
method3
method4
if both group passed then method5 test will execute
method3
method4

 

Source: http://selenium-makeiteasy.blogspot.com