Home » TestNG @BeforeTest Annotation

TestNG @BeforeTest Annotation

by Online Tutorials Library

TestNG @BeforeTest Annotation

You have a requirement when you automate the test cases, you want your data to be deleted first which you submitted. For example, when you run the test case, you will fill the details in a form, and the data is saved in a database. When you run the test case again, then you get an error that “data already exists“.

@BeforeTest: The method which comes under the @BeforeTest annotation will be executed first before any test belonging to that folder.

Let’s understand through an example.

First case: When we place the @BeforeTest annotated method in the beginning.

Step 1: Open the Eclipse.

Step 2: We create two java projects, i.e., it_department.java and hr_department.java.

it_department.java

In the above code, one method is placed under the @BeforeTest annotation which will be executed first before all the test methods available in the it_department.

hr_department.java

Step 3: Create the testng.xml file. testng.xml file

Step 4: Run the testng.xml file. Right click on the testng.xml and then move the cursor down to Run As and then click on the 1 TestNG Suite.

Output

TestNG @BeforeTest Annotation

The above output shows that the method in @BeforeTest annotation is executed first before all the test cases of it_department.

Second case: When we place the @BeforeTest annotated method at the end.

Source code

In the above code, we place the @BeforeTest annotated method at the end.

Output

TestNG @BeforeTest Annotation

In the above output, we conclude that @BeforeTest annotated method is executed first, So, we conclude that @BeforeTest annotated method is placed anywhere, it will be executed first.


Next TopicTestNG Annotations

You may also like