mvn传参数

执行mvn test时给程序传参示例:

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>helloworld</groupId>
<artifactId>helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.10</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>QA</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<auto.environment>QA environment</auto.environment>
</properties>
</profile>
<profile>
<id>DEV</id>
<properties>
<auto.environment>DEV environment</auto.environment>
</properties>
</profile>
</profiles>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>
testng.xml
</suiteXmlFile>
</suiteXmlFiles>
<systemPropertyVariables>
<deviceType>iOS</deviceType>
<environment>${auto.environment}</environment>
</systemPropertyVariables>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>

取参:

1
2
3
4
5
6
7
8
9
10
11
public class Hi {

@Test
public void simpleTets() {
String deviceType = System.getProperty("deviceType");
String environment = System.getProperty("environment");

System.out.println("========= deviceType: "+ deviceType);
System.out.println("========= environment: "+ environment);
}
}

testng.xml

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="helloworld.Hi"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

有两种传参方式,-DdeviceType=android-P DEV,相应的默认值的设置也有两种方式,个人实际工作中倾向于第一种:

1
mvn test -DdeviceType=android -P DEV --settings /Users/tracenote/.m2/setting.xml

输出:

========= deviceType: android
========= environment: DEV environment

不传参数,程序输出默认值:

1
mvn test   --settings /Users/tracenote/.m2/setting.xml

输出:

========= deviceType: iOS
========= environment: QA environment