Naman
Naman

Reputation: 32036

BeforeTest would not run before every Test method of the class in <test> tag

Inquiring further into SO-4310964 , I went through the description of annotations at test.org.

@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the test tag is run.

Now what we have in our code is as follows :

MyTests.java

public class MyTests {
    @BeforeTest
    public void preTest(){
        //Want to perform some action, suppose clear a Hashmap
        System.out.println("Before Test Called!");
    }

    @Test(groups = {"SanityTests"}, testName = "test1")
    public void Test1(){
            System.out.println("test1");
    }

    @Test(groups = {"SanityTests"}, testName = "test2")
    public void Test2(){
            System.out.println("test2");
    }
}

Sanity-Test.xml

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="SanityTests" verbose="1" >
    <listeners>
        <listener class-name="com.android.MyTestsListener" />
    </listeners>

    <test name="sanityAndroid">
        <classes>
            <class name="com.android.MyTests" />
        </classes>
    </test>
</suite>

Note : I know that @BeforeMethod solves the problem. But to my understanding the link details that the @BeforeTest[preTest] method would run before any @Test[test1,test2] method which belong to the class inside the <test> tag. Where am I going wrong?

Upvotes: 0

Views: 2711

Answers (1)

Amanpreet Kaur
Amanpreet Kaur

Reputation: 1074

BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run

Focus on the "Before any test method", not every test method.

Now, if the test tag have 2 classes as follow:

<test name="sanityAndroid">
    <classes>
        <class name="com.android.MyTests1" />
        <class name="com.android.MyTests2" />
    </classes>
</test>

Class MyTest1 have @Test methods as test1 , test2 and Class MyTest2 have @Test methods as test3 , test4.

So, BeforeTest method will run before any of the test methods i.e test1, test2, test3, test4 belonging to classes i.e. MyTest1, MyTest2 inside the <test> tag.

Execution becomes BeforeTest -> (test1, test2, test3, test4) acc to dependency.

Similar to this is AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.

Upvotes: 3

Related Questions