![]() |
VOOZH | about |
@BeforeMethod is one of the TestNG Annotations. As the name itself defines, @BeforeMethod is executed before each test method within a test class. Suppose there are n test methods within a test class, then n times the @BeforeMethod annotated method will be invoked. This annotation allows developers to specify various actions to be taken before test methods are run.
Let's understand the @BeforeMethod annotation through an example.
Step 1: In a Maven Project, create a TestNG Class that contains @BeforeMethod.
CalculatorTest.java (@BeforeMethod)
Now, let's explain what this code does:
Package Declaration: The code is in the com.geeksforgeeks.test package.
Imports: The code imports annotations and classes from the TestNG framework (org.testng.annotations.BeforeMethod and org.testng.annotations.Test).
CalculatorTest Class: This is the main test class. It contains test methods and setup method.
NewTest Inner Class:
setUp Method (@BeforeMethod):
Test Methods (@Test):
When you run this test class, you'll see output lines for each test method execution, along with the setup message from the setUp() method.
Step 2: Now, we create the testng.xml file to configure the CalculatorTest class.
Step 3: Run the CalculatorTest file. Right click on the CalculatorTest and move the cursor down to Run As and then click on the 1 TestNG Suite.
As we can observe in above code, the execution of different tests or methods is in proper order. First Addition() Test is executed, then division() test, after that multiplication() test and at the end Subtraction Test() will be executed.