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