如何在testng.xml中透過名稱和萬用字元執行TestNG類?
testng.xml 的格式為 <classes>,我們在此定義所有要執行的測試類。在 <classes> 中的類中沒有提供正則表示式的特定方法。但是,有一些解決方法可用於執行類中的特定 @Test。TestNG 支援在 include、exclude 和 package 標籤中的正則表示式。
這裡,問題陳述是當用戶只想執行名稱格式相同的特定類時,例如類的初始名稱應相同。例如,使用者希望執行所有名稱以 NewTest 開頭的類。
在本教程中,我們將討論如何執行所有名稱以 NewTest 開頭的類。
上述問題的解決方案可以在 beanshell 指令碼中實現。使用者可以使用 <method−selectors> 標籤而不是 <classes> 在 testng.xml 中提供簡單的程式碼。它將在執行時進行評估,並獲取應執行的類名。
解決此問題的方法/演算法
步驟 1:建立 3 個 TestNG 類 - NewTestngClass、NewTestNGClass1 和 OrderofTestExecutionInTestNG。
步驟 2:在所有類中編寫 @Test 方法。
步驟 3:現在建立如下所示的 testNG.xml。
步驟 4:現在,執行 testNG.xml 或直接在 IDE 中執行 TestNG 類,或者使用命令列進行編譯和執行。
示例
以下程式碼演示如何僅從大型套件中執行 1 個測試方法
src/ NewTestngClass.java
import org.testng.annotations.Test; public class NewTestngClass { @Test public void testCase1() { System.out.println("in test case 1 of NewTestngClass"); } }
src/ NewTestngClass1.java
import org.testng.annotations.Test; public class NewTestngClass { @Test public void testCase1() { System.out.println("in test case 1 of NewTestngClass1"); } }
src/ NewTestngClass.java
import org.testng.annotations.Test; public class OrderofTestExecutionInTestNG { @Test public void testCase1() { System.out.println("in test case 1 of OrderofTestExecutionInTestNG"); } }
testng.xml
這是一個用於組織和執行 TestNG 測試用例的配置檔案。
當只需要執行有限的測試而不是完整的套件時,它非常方便。
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1" parallel = "none"> <test name = "test1" preserve-order = "true"> <method-selectors> <method-selector> <script language="beanshell"><![CDATA[ method.getDeclaringClass().getSimpleName().startsWith("NewTest") ]]> </script> </method-selector> </method-selectors> </test> </suite>
輸出
in test case 1 of NewTestngClass in test case 1 of NewTestngClass1 =============================================== Suite1 Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 ===============================================
廣告