工作中在使用Java+Selenium+TestNG+Maven+Jenkins做WebUI自動化測試的過程中,想要配置兩個參數化建構。第一個就是執行Testng的XML檔案參數;另一個參數就是環境參數,該參數對應WebUI自動化測試的環境。
實際效果:Jenkins給定不同的XML檔案名稱、環境參數後,會執行指定XML檔案,指定環境的測試。
首先Jenkins需要安裝插件Build With Parameters (輸入框式的參數)或者 Persistent Parameter (下拉框式參數)。
然後在maven項目配置頁面,選擇下圖選項:

環境資料配置如下:
此時将環境參數配置好。回到maven pom檔案配置參數,這裡使用了profile去實作參數化。
<!-- 不同的打包環境 -->
<profiles>
<!-- 測試環境,預設激活 -->
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<!-- 深圳環境 -->
<profile>
<id>sz</id>
<properties>
<env>sz</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault><!--預設啟用的是sz環境配置-->
</activation>
</profile>
<!-- 廣西環境 -->
<profile>
<id>gx</id>
<properties>
<env>gx</env>
</properties>
</profile>
<!-- 示範環境 -->
<profile>
<id>example</id>
<properties>
<env>example</env>
</properties>
</profile>
</profiles>
複制
然後我的思路是想法是通過evn配置檔案讀取各個環境對應的所有配置,
是以在main目錄的resource檔案夾下建立了evn.properties檔案,然後建立了filters檔案夾去管理所有環境的資料配置,檔案結構和檔案資料如下
結構
evn.properties檔案資料如下
# Environment
test.host=${test.host}
# 資料源配置
datasource.url=${jdbc-url}
datasource.username==${jdbc-usernamel}
datasource.password==${jdbc-password}
datasource.driver-class-name=com.mysql.cj.jdbc.Driver
複制
filters-sz配置檔案資料如下
# ip
test.host=http://zhan.zzxes.com.cn/
# 資料庫
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///campus_terminal?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username=root
password=123
複制
項目實際取參代碼如下:
public String GetHost(String url) {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("env.properties");
properties = new Properties();
try {
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
String host = properties.getProperty("test.host");
System.out.println(host);
return host;
}
複制
此時,去Jenkins建構項目時,就可以去選擇對應的環境來進行建構。建構後會自動打開對應域名的環境。
接下來進行測試用例的選擇執行,在maven中添加配置
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<argLine>-Dfile.encoding=UTF-8</argLine>
<encoding>UTF-8</encoding>
<suiteXmlFiles>
<!--suppress UnresolvedMavenProperty -->
<suiteXmlFile>${project.basedir}/src/test/testsuite/${RunTest}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
複制
此時,在Jenkins中添加對應選擇參數
最後,我們在建構預步驟中加入指令,如下圖
這是時候,Jenkins建構maven項目時,就可以選擇對應參數去建構,可以根據需要去執行對應環境的對應子產品的用例。
後發現在建構成功後,整個測試套件還會重複build一次,排查問題後,應該是在建構指令設定時不應該使用test 直接使用package即可
clean package -Dmaven.test.skip=true -P%env% -DRunTest=%RunTest%