@BeforeTest is one of the TestNG Annotations. As the name defines, @BeforeTest is executed before the execution of all the @test annotated methods inside a TestNG Suite. This annotation allows developers to specify various actions to be taken before the execution of all the @test annotated methods inside a TestNG Suite.
Let’s understand the @BeforeTest annotation through an example.
Step 1: In the Maven project, create a TestNG Class that contains @BeforeTest.
Before_Test1.Java
package com.geeksforgeeks.test; import org.testng.annotations.Test; import org.testng.annotations.BeforeTest; public class Before_Test1 { @BeforeTest public void beforeTest() { System.out.println("This method will be executed before the execution of all @Test annotated methods"); } @Test public void test1() { System.out.println("Test1 Executed"); } @Test public void test2() { System.out.println("Test2 Executed"); } }
Now, let’s explain what this code does:
- Package Declaration: Before_Test1 Class is on the com.geeksforgeeks.test package.
- Imports: Before_Test1 Class imports annotations and classes from the TestNG framework (org.testng.annotations.BeforeMethod and org.testng.annotations.Test).
- Before_Test1 Class: This is the main test class. It contains test methods and beforeTest method.
beforeTest (@BeforeTest):
- This method is annotated with @BeforeTest, indicating that it should be executed before test execution this suite contains many classes.
- It prints this "This method will be executed before the execution of all @Test annotated methods" statement.
Test Methods (@Test):
- Each test method is annotated with @Test, indicating that it is a test case.
- There are two test methods: test1() and test2().
- Each test method prints their respective statement.
After performing the operation, the result is printed to the console.
Step 2: Now, we create the AnnotationsTest.xml file to configure the Before_Test1 Class.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="suite"> <test name="test1"> <classes> <class name="com.geeksforgeeks.test.Before_Test1" /> </classes> </test> </suite>
Step 3: Run the AnnotationsTest.xml. Right click on the AnnotationsTest.xml file, move the cursor down to Run As and then click on the TestNG Suite.
.png)