如何使用 TestNG @After 註解?
一個 TestNG 類可以包含各種 @After TestNG 方法。例如:@AfterTest @AfterSuite @AfterClass @AfterMethod 等等。
本文將解釋不同 TestNG 方法的執行順序。
TestNG 包含以下 @After 方法來支援主要的 @Test 方法。@After 方法的執行順序應如下所示
<test1> <AfterMethod> <AfterClass> <AfterTest> <AfterSuite>
此順序中的關鍵點是
首先,在上面的示例中,第一個 @test() 方法被執行。
AfterSuite() 方法只執行一次。
同樣,AfterClass() 和 AfterTest() 方法也只執行一次。
AfterMethod() 方法針對每個測試用例(每次針對新的 @Test)執行,但在執行測試用例之後。
解決此問題的方法/演算法
步驟 1:匯入 org.testng.annotations.* 用於 TestNG。
步驟 2:編寫一個註釋為 @test 的註解。
步驟 3:為 @test 註解建立一個名為 test1 的方法。
步驟 4:對 test2 和 test3 重複上述步驟。
步驟 5:編寫不同的註解及其相應的方法。例如:@AfterClass、@AfterMethod、@AfterSuite
步驟 5:現在建立如下所示的 testNG.xml。
步驟 6:現在,執行 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");
}
@AfterMethod
public void afterMethod() {
System.out.println("in afterMethod");
}
@AfterClass
public void afterClass() {
System.out.println("in afterClass");
}
@AfterTest
public void afterTest() {
System.out.println("in afterTest");
}
@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 test case 1 in afterMethod in test case 2 in afterMethod in afterClass in afterTest in afterSuite
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP