从pom.xml java获取变量

时间:2014-10-20 07:11:14

标签: java xml eclipse maven

我正在使用eclipse和maven在移动网页上进行移动自动化测试。

我在pom.xml中定义了以下内容

<properties>
    <MY_VARIABLE>www.google.com/</MY_VARIABLE>
</properties>

但是当我使用

来调用它时
String testurl1 = System.getProperty("MY_VARIABLE");

似乎总是返回null。

我还尝试了以下定义变量的方法

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <systemPropertyVariables>
        <MY_VARIABLE>www.google.com</MY_VARIABLE>
        </systemPropertyVariables>
    </configuration>
</plugin>

但仍然将值变为null。

我可以使用一些帮助 感谢。

1 个答案:

答案 0 :(得分:3)

你的配置在eclipse中不起作用,因为没有好的m2e支持surefire。 maven surefire插件会创建一个新进程,并为其提供systemPropertyVariables。如果从命令行运行测试,则配置将起作用,例如

mvn surefire:test

为了让它在两个世界中运行(命令行和日食)我这样做......

  1. 创建src/test/resources/maven.properties
  2. 编辑maven.properties文件并在其中添加所需的属性,例如

    project.build.directory=${project.build.directory}
    MY_VARIABLE=${MY_VARIABLE}
    
  3. 为测试资源启用资源过滤

    <build>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
        ...
    </build>
    
  4. 在测试中加载属性并访问它们

     Properties mavenProps = new Properties();
     InputStream in = TestClass.class.getResourceAsStream("/maven.properties");
     mavenProps.load(in);
    
     String buildDir = mavenProps.getProperty("project.build.directory");
     String myVar = mavenProps.getProperty("MY_VARIABLE");