TestNG 方法的执行顺序是什么?
一个TestNG类可以包含各种TestNG方法,例如:
@BeforeTest
@AfterTest
@BeforeSuite
@BeforeClass
@BeforeMethod
@test 等。
在这篇文章中,我们将了解不同TestNG方法的执行顺序。
TestNG 提供以下方法来支持主要的 @Test 方法。执行顺序应如下所示:
<beforeSuite> <beforeTest> <beforeClass> <beforeMethod> <test1> <afterMethod> <afterClass> <afterTest> <afterSuite>
此顺序中的关键点:
首先,beforeSuite() 方法只执行一次。
afterSuite() 方法也只执行一次。
beforeTest()、beforeClass()、afterClass() 和 afterTest() 方法也只执行一次。
beforeMethod() 为每个测试用例(每次新的 @Test)执行,但在执行测试用例之前。
afterMethod() 为每个测试用例(每次新的 @Test)执行,但在执行测试用例之后。
在 beforeMethod() 和 afterMethod() 之间,每个测试用例(@Test 注解的方法)都会执行。
解决此问题的方法/算法:
步骤 1 - 为 TestNG 导入 org.testng.annotations.*。
步骤 2 - 编写注解为 @test
步骤 3 - 为 @test 注解创建一个方法,例如 test1。
步骤 4 - 对 test2 和 test3 重复这些步骤。
步骤 5 - 编写不同的注解及其各自的方法,例如 @beforeSuite, @afterSuite, @beforeTest, @afterTest, @beforeClass, @afterClass, @beforeMethod, @afterMethod
步骤 6 - 现在创建如下所示的 testNG.xml。
步骤 7 - 运行 testNG.xml 或直接在 IDE 中运行 TestNG 类,或者使用命令行编译并运行它。
示例
使用以下代码显示不同 TestNG 方法的顺序:
import org.testng.annotations.*;
import org.testng.annotations.Test;
public class OrderofTestExecutionInTestNG {
// test case 1
@Test
public void testCase1() {
System.out.println("in test case 1");
}
// test case 2
@Test
public void testCase2() {
System.out.println("in test case 2");
}
@BeforeMethod
public void beforeMethod() {
System.out.println("in beforeMethod");
}
@AfterMethod
public void afterMethod() {
System.out.println("in afterMethod");
}
@BeforeClass
public void beforeClass() {
System.out.println("in beforeClass");
}
@AfterClass
public void afterClass() {
System.out.println("in afterClass");
}
@BeforeTest
public void beforeTest() {
System.out.println("in beforeTest");
}
@AfterTest
public void afterTest() {
System.out.println("in afterTest");
}
@BeforeSuite
public void beforeSuite() {
System.out.println("in beforeSuite");
}
@AfterSuite
public void afterSuite() {
System.out.println("in afterSuite");
}
}testng.xml
这是一个配置文件,用于组织和运行 TestNG 测试用例。当只需要执行有限的测试而不是完整的套件时,它非常方便。
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1"> <test name = "test1"> <classes> <class name = "OrderofTestExecutionInTestNG"/> </classes> </test> </suite>
输出
in beforeSuite in beforeTest in beforeClass in beforeMethod in test case 1 in afterMethod in beforeMethod in test case 2 in afterMethod in afterClass in afterTest in afterSuite
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP