📜  TestNG @BeforeMethod注释

📅  最后修改于: 2021-01-11 12:04:05             🧑  作者: Mango

TestNG @BeforeMethod注释

@BeforeMethod特定于类而不是XML文件。 @BeforeMethod带注释的方法将在每个测试方法执行之前调用,其中测试方法不过是一个测试用例。假设一个类中有四个测试方法,然后在每个测试方法执行之前执行@BeforeMethod注释方法。如果有四个测试方法,则将调用四次@BeforeMethod带注释的方法。

让我们通过示例了解@BeforeMethod批注。

步骤1:打开Eclipse。

步骤2:我们创建一个包含@BeforeMethod批注的简单Java项目。

Before_Methods.java

package com.javatpoint;
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);
  }
}

在上面的代码中,我们创建了@BeforeMethod带注释的方法,该方法将在执行每个测试方法(即sum()和different()测试方法)之前调用。

步骤3:现在,我们创建testng.xml文件以配置Before_Methods类。

testng.xml文件








 
 

步骤4:运行testng.xml文件。右键单击testng.xml文件,然后将光标向下移动到Run As ,然后单击1 TestNG Suite

输出量

在上面的输出中,差分()方法在sum()之前执行,因为我们知道TestNG以字母顺序运行测试方法,@BeforeMethod带注释的方法在每种测试方法执行之前被调用,即,difference()和和()。