@BeforeClass is one of the TestNG Annotations. As the name defines, @BeforeClass is executed before all the methods of the current class start their execution. This annotation allows developers to specify various actions to be taken before all the methods of the current class start their execution.
Let's understand the @BeforeClass annotation through an example.
Step 1: Create a Maven Project and create a TestNG Class that contains @BeforeMethod.
1. Before_Class1.Java
package com.geeksforgeeks.test; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; public class Before_Class1 { @BeforeClass public void brforeClass() { System.out.println("Below are types of frontend testing"); } @Test public void fun1() { System.out.println("Unit Testing"); } @Test public void fun2() { System.out.println("Integration Testing:"); } @Test public void fun3() { System.out.println("Regression Testing"); } public void fun4() { System.out.println("System Testing"); } }
Step 2. create Before_Class2.Java as the same.
package com.geeksforgeeks.test; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; public class Before_Class2 { @BeforeClass public void beforeClass() { System.out.println("Below are types of backend testing"); } @Test public void fun1() { System.out.println("Structural testing"); } @Test public void fun2() { System.out.println("Functional Testing"); } @Test public void fun3() { System.out.println("Non-Functional Testing"); } }
Now, let's explain what this code does:
- Package Declaration: Both Class is on the com.geeksforgeeks.test package.
- Imports: Both Class imports annotations and classes from the TestNG framework (org.testng.annotations.BeforeMethod and org.testng.annotations.Test).
Before_Class1 Class
- This is the main test class.
- It contains test methods and before class method.
- beforeClass (@BeforeMethod):
- This method is annotated with @BeforeClass, indicating that it should be executed before class execution.
- It prints this " These are the type of frontend testing" statement.
- Test Methods (@Test):
- Each test method is annotated with @Test, indicating that it is a test case.
- There are four test methods: fun1(), fun2(), fun3() and fun4().
- Each test method prints their respective statement.
- After performing the operation, the result is printed to the console.
Similarly Before_Class2. Java Class Execute
Step 3: Now, we create the AnnotationsTest.xml file to configure the Before_Class1 class and Before_Class2 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_Class1" /> <class name="com.geeksforgeeks.test.Before_Class2" /> </classes> </test> </suite>
Step 4: Run the AnnotationsTest.xml. Right click on the AnnotationsTest.xml file, move the cursor down to Run As and then click on the 1 TestNG Suite.
-min.png)