如何從命令列執行 TestNG?
TestNG 允許從命令列 **(cmd)** 執行測試套件。以下是一組必須滿足的先決條件,以便從命令列執行測試套件:
應建立 **testng.xml** 檔案以定義測試套件和要執行的測試類。
所有依賴的 **jar** 檔案都應位於專案資料夾內。它包括 **testng.jar**、**jcommander.jar** 和測試用例中使用的任何其他 **jar** 檔案。
編譯後儲存 **.class** 檔案的 **bin** 或 **out** 資料夾的路徑。
解決此問題的方法/演算法
**步驟 1** - 建立具有不同 **@Test** 方法的不同測試類
**步驟 2** - 編譯 **class**;它將在 **IntelliJ** 中建立 out 資料夾,在 **Eclipse** 中建立 bin 資料夾。
**步驟 3** - 將所有 **jar** 檔案放在 **lib** 資料夾中。
**步驟 4** - 現在建立如下所示的 **testng.xml**。
**步驟 5** - 開啟 **cmd**。
**步驟 6** - 使用 **cd <project_path>** 導航到專案路徑
**步驟 7** - 執行以下命令:
java -cp <path of lib>; <path of out or bin folder> org.testng.TestNG <path of testng>/testng.xml
示例
以下程式碼演示瞭如何從命令列執行 TestNG:
src/ OrderofTestExecutionInTestNG.java
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"); } }
src/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>
執行命令
java -cp C:\Users\********\IdeaProjects\TestNGProject\lib\*;C:\Users\*** *****\IdeaProjects\TestNGProjectct\out\production\TestNGProject org.testng.TestNG src/testng.xml
如果使用者沒有使用 **cd <project path>** 導航到測試專案路徑,則可以在命令中提供完整路徑,如上所示。但是,如果使用者已在測試專案路徑中,則可以修改命令如下:
java -cp .\lib\*;.\out\production\TestNGProject org.testng.TestNG src\testng.xml
輸出
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 =============================================== Suite1 Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 ===============================================
廣告