Issue in using @BeforeTest annotation in testng

2019-09-01 22:04发布

问题:

I am writing automation code for my mobile site.

Class1:-

public class Sample{

    @BeforeTest
    public void createUser(){
    // code to create user
    }

    @Test
    public void verifyUser(){
    // code to verify user
    }


    @AfterTest
    public void deleteUser(){
    // code to delete user
    }

}

Like Class1. I have different classes such as Class2, Class3, Class4.

testing.xml

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

<suite name="Suite1" verbose="1">
    <test name="Regression1" parallel="false" preserve-order="true">
        <classes>
            <class name="Class1"/>
            <class name="Class2"/>          
            <class name="Class3"/>
            <class name="Class4"/>
        </classes>
    </test>
</suite>

Command to run:-

mvn -Dtests=testing.xml test

when i run above command, @BeforeTest from Class1, Class2, Class3, Class4 are called first. It means 4 users are created firstly before running any test. Then only Class1 Test is running then Class2 and so on. Atlast @AfterTest from all classes are running(deleting all user atlast).

I don't want this scenario.

I need the following way to run my each test:-

  1. create of user
  2. verify of user
  3. delete of user

I need my Class1 executed first fully then Class2 and so on.

Is there any change in annotation for testng i have to do?

回答1:

Use BeforeMethod instead of BeforeTest. The BeforeTest method will run before your <test> tag in testng.xml and not before your @Test method. And also use AfterMethod instead of AfterTest of course.

Check my answer for another similar question: Difference between BeforeClass and BeforeTest in TestNG