TestNG教程

TestNG @BeforeMethod

TestNG @BeforeMethod 注释

@BeforeMethod 特定于类而不是 XML 文件。 @BeforeMethod 注释的方法将在每个测试方法执行之前调用,其中测试方法只是一个测试用例。假设一个类中有四个测试方法,那么在每个测试方法执行之前都会执行@BeforeMethod 注解的方法。如果有四个测试方法,那么会调用四次@BeforeMethod注解的方法。
我们通过一个例子来理解@BeforeMethod注解
第 1 步: 打开 Eclipse。
第 2 步: 我们创建一个包含 @BeforeMethod 注释的简单 Java 项目。
Before_Methods.java
package com.lidihuo;
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() 和 difference() 测试方法)执行之前调用。
第 3 步: 现在,我们创建 testng.xml 文件来配置 Before_Methods 类。
testng.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<test name="Before Methods">
<classes>
<class name="com.lidihuo.Before_Methods"/>
</classes>
</test> <!--Test-->
</suite> <!--Suite-->
    
第 4 步: 运行 testng.xml 文件。右键单击 testng.xml 文件并将光标向下移动到 Run As,然后单击 1 TestNG Suite。
输出
TestNG @BeforeMethod Annotation
在上面的输出中,difference()方法在 sum() 之前执行,因为我们知道 TestNG 按字母顺序运行测试方法,@BeforeMethod 注释方法在每个测试方法执行之前调用,即差异() 和 sum()。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4