【问题标题】:Getting variables from pom.xml java从 pom.xml java 中获取变量
【发布时间】:2023-04-05 10:45:01
【问题描述】:

我正在使用 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。

我需要一些帮助 谢谢。

【问题讨论】:

  • 您应该为此使用属性文件
  • 我认为变量名是混用的。您使用我们的属性 MY_VARIABLE 但在surefire插件配置它的MY_URL / MY_VARIABLE?你使用surefire插件的方式应该可以工作,你可能只是使用了错误的名字?
  • @wemu 我没有在我的代码中使用 MY_VARIABLE 两次,无论是第一种方法还是第二种方法...
  • @RC。你能再解释一下吗..
  • 只是您拥有的 xml 无效:www.google.com

标签: java xml eclipse maven


【解决方案1】:

您的配置在 Eclipse 中将不起作用,因为没有对肯定火的良好 m2e 支持。 maven surefire 插件派生了一个新进程并为其提供systemPropertyVariables。如果您从命令行运行测试,您的配置将起作用,例如

mvn surefire:test

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

  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");
    

【讨论】:

  • 所以我必须在 maven.properties 文件中添加这一行 MY_VARIABLE = www.google.com 以及如何在 mavenProps.load(in); 之后调用变量命令...
  • 感谢它为您解决了一个问题,我可以通过 ${MY_VARIABLE} 使用我的 pom.xml 中的 maven.properties 中的 MY_VARIABLE 吗?
  • @Ram 没错,因为当 maven 过滤 maven.properties 文件时,它会将所有出现的 ${...} 替换为属性值。查看maven.apache.org/plugins/maven-resources-plugin/examples/… 了解更多信息。
  • 你能告诉我如何调用我在surefire插件中定义的变量是否与mavenProps.get()相同,因为System.getPropoerty()不起作用
  • 我更新了我的答案,以解释为什么在 eclipse 中启动 junit 测试时它不起作用。
猜你喜欢
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 2014-12-08
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
  • 2016-04-15
相关资源
最近更新 更多