什麼是 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 − 匯入 org.testng.annotations.* 用於 TestNG。
步驟 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