@Before Suite and @BeforeTest methods are not called if groups are executed in TestNG

Viewed 4485

Below is my XML file and Demo Class. Precondition() method will run before demo1() method and postCondition() method will run after demo1() method. Same process is for demo2(). But when i run the code, BeforeSuite and BeforeTest Methods are not Called. Why.? How to call them ?

Output :           
Before Method is executing                                                       
DEMO -1   
After Method is executing  
Before Method is executing  
DEMO 2  
After Method is executing
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="Test">
        <groups>
            <run>
                <include name = "Hey"></include>
            </run>
        </groups>
        <classes>
            <class name="practicepackage.Demo"/>
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->  
package practicepackage;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Demo {

    @BeforeSuite
    public void beforeSuite(){
        System.out.println("Before Suite method is being launched");
    }

    @BeforeTest
    public void beforeTest(){
        System.out.println("Before Test Method is being luanched");
    }

    @BeforeMethod(groups = {"Hey"})
    public void PreCondition(){
        System.out.println("Before Method is executing");
    }

    @Test (groups = {"Hey"})
    public void demo1(){
        System.out.println("DEMO -1 ");
    }

    @Test(groups = {"Hey"})
    public void demo2(){
        System.out.println("DEMO 2");
    }

    @AfterMethod(groups = {"Hey"})
    public void postCondition(){
        System.out.println("After Method is executing");
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="Test">
        <groups>
            <run>
                <include name = "Hey"></include>
            </run>
        </groups>
        <classes>
            <class name="practicepackage.Demo"/>
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->
1 Answers

In order to ensure that @BeforeSuite and @BeforeTest are executed all the time, please enable the attribute alwaysRun=true for these annotations.

This is required because when you run through groups, these configuration methods wont be selected by TestNG until and unless they are part of the group which you selected.

Group selection in TestNG can be visualised as a sort of filtering mechanism in TestNG that lets you tell TestNG the criteria for filtering, when it decides which tests to run.

Related