C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
TestNG @BeforeMethod AnnotationThe @BeforeMethod is specific to a class not to an XML file. The @BeforeMethod annotated method will be invoked before the execution of each test method where the test method is nothing but a test case. Suppose there are four test methods in a class then the @BeforeMethod annotated method is executed before the execution of each test method. If there are four test methods, then four times @BeforeMethod annotated method will be invoked. Let's understand the @BeforeMethod annotation through an example. Step 1: Open the Eclipse. Step 2: We create a simple java project which contains @BeforeMethod annotation. Before_Methods.java
package com.TheDeveloperBlog;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Before_Methods
{
int a=10;
int b=9;
@BeforeMethod
public void before_method()
{
System.out.println("This method will be invoked before every test method");
}
@Test
public void sum()
{
int sum;
sum=a+b;
System.out.print("Sum of a and b is : "+sum);
}
@Test
public void difference()
{
int diff;
diff=a-b;
System.out.println("Difference of a and b is :"+diff);
}
}
In the above code, we created the @BeforeMethod annotated method which will be invoked before the execution of each test method, i.e., sum() and difference() test methods. Step 3: Now, we create the testng.xml file to configure the Before_Methods class. testng.xml file Step 4: Run the testng.xml file. Right click on the testng.xml file and move the cursor down to Run As and then click on the 1 TestNG Suite. Output
In the above output, difference() method executes before the sum() as we know that TestNG runs the test methods in alphabetical order, the @BeforeMethod annotated method is invoked before the execution of each test method, i.e., the difference() and sum().
Next TopicTestNG Annotations
|