https://sq.163yun.com/blog/article/173632756223238144
目前很多項目組的測試代碼工程都是采用MAVEN+TESTNG的方式構造的。
因此測試代碼project內的pom.xml就必不可少的有以下配置:
在pom.xml中配置testNG的依賴,以便自動下載應用於project <dependencies> [...] <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8.8</version> <scope>test</scope> </dependency> [...] </dependencies> |
當然還需要有build中的插件配置:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.16</version> <configuration> <suiteXmlFiles> <suiteXmlFile>src/test/resources/basic.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin>
|
簡單說下maven-surefire-plugin是個什么插件,它是一個用於mvn 生命周期的測試階段的插件,可以通過一些參數設置方便的在testNG或junit下對測試階段進行自定義。然而大家的時候一般都會按我上面的例子去配置,很少用到一些靈活的參數,這樣的會不利於我們的測試效率,違背了maven-surefire-plugin插件設計的初衷。
上面表格中的配置的意思就是默認指定了一個叫basic.xml測試集合。
執行命令:mvn clean test
這樣執行的就是我想要的basci.xml里面的測試用例。
這樣可以滿足我們執行1個測試集的需求,然而當我們的工程里有多個測試集例如:a.xml b.xml c.xml的時候該怎么辦呢?
第一、首先能想到的一個最原始的辦法:修改pom.xml文件
將 <suiteXmlFile>src/test/resources/basic.xml</suiteXmlFile>這一行更改為a.xml,或者b.xml 然后執行mvn clean test。
操作步驟演示如下:
然而這樣的話如果我想在持續集成里面連續運行多個執行集的話就不方便這樣操作,因為需要使用shell語言去控制你要運行測試的命令,這樣的話就想到兩種方式:用sed替換文本,或者直接復制多個pom.xml文件,用的時候重命名一下,這里選用第二種方式。
第二、在工程下構造多個xml文件
例如pom_a.xml pom_b.xml,他們內容的區別就是maven-surefire-plugin的suiteXmlFile屬性分別指向a.xml和b.xml。然后運行的時候使用對應的pom*.xml文件。
操作步驟演示如下:
但是這樣的話還是會造成多個pom.xml文件,並且如果這些pom文件中涉及到depend依賴更新,就全部都需要更新一遍,造成不必要的維護工作量。而且感覺這樣總不是根本辦法。其實maven-surefire-plugin本身就支持指定不同的測試套件xml,只需要在pom中配置一下,使用相應的命令就可以調用執行對應的測試套件了。
第三、maven-surefire-plugin設置靈活的測試套件參數
將上述pom.xml中的 <suiteXmlFile>src/test/resources/basic.xml</suiteXmlFile>改為如下配置 <suiteXmlFile>${suiteXmlFile}</suiteXmlFile>
然后在pom.xml中的properties里加一行<suiteXmlFile>testng.xml</suiteXmlFile>
注意testng.xml不需要改成對應的測試套件名稱,只是定義了一個變量,因此執行不同的測試套件時不需要修改pom.xml文件。
pom.xml修改后如下所示:
<properties> <suiteXmlFile>testng.xml</suiteXmlFile> </properties> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.16</version> <configuration> <argLine>-Dfile.encoding=UTF-8</argLine> <suiteXmlFiles> <suiteXmlFile>${suiteXmlFile}</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> </plugins>
|
執行:mvn clean test -DsuiteXmlFile=src/test/resources/xml/a.xml 就可以調用你對應的a.xml中包含的測試用例了。
操作步驟演示如下:
是不是很簡單呢,快快配起來吧
另外maven-surefire-plugin支持的一些常用命令參數列表見下:
mvn clean test -Dtest=Testabc 其中Testabc表示當前測試方法所在的測試類,不需要擴展名,即運行Testabc.java中的所有測試方法。
mvn clean test -Dtest=Test*c 其中以Test開頭c結尾的所有類的所有測試方法都會運行。
更多maven-surefire-plugin的高級功能等待廣大筒子進一步探索~