首页 > 解决方案 > 如何在每个环境中配置 Maven Surefire 中的环境变量?

问题描述

我正在尝试在竹子构建计划期间运行 Maven 测试阶段。我的测试依赖于我在 pom.xml 中配置的一组环境变量。但是,这些值仅适用于一个环境,我想在多个环境(不同的主机 IPS 等)上执行相同的测试。我的 Pom.xml 看起来像这样:

<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>

<configuration>

 <environmentVariables>
    <variableName>variableValue</variableName>
  </environmentVariables>

</configuration>

竹计划构建有一个阶段,它使用简单的“mvn clean test”命令行执行 maven 测试阶段。我有超过 10 个环境变量,所以我希望避免将这些变量值传递给命令行,因为它会使它变得很长。如何配置 maven Surefire 以包含一组以上的环境变量(一组用于测试,一组用于生产),这样我就可以根据我执行的竹子构建计划传递到命令行以获取环境变量。所以类似: mvn clean -D test。

标签: mavenbamboomaven-surefire-plugin

解决方案


兜售问题的最佳解决方案是使用配置文件过滤和属性文件。您需要配置以下文件夹树:

  • 源代码
    • 测试
      • 爪哇
      • 配置文件资源
      • 资源

您需要将一个属性文件放入资源中,并将变量值声明为配置文件资源的链接:variable={value},并且您需要在配置文件资源中为每个环境创建单独的属性文件。

然后将其包含在您的 pom.xml 文件中:

  <profiles>
    <profile>
        <id>Name of first profile</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <filter.properties>env1.properties</filter.properties>
        </properties>
    </profile>
    <profile>
        <id>Name of second profile</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <properties>
            <filter.properties>env2.properties</filter.properties>
        </properties>
    </profile>
</profiles>

<build>
    <filters>
        <filter>src/test/profile-resources/${filter.properties}</filter>
    </filters>
</build>

然后,您可以使用激活配置文件的 -P Maven 命令自动调用每个配置文件。示例: mvn verify -P "配置文件名称"。

相关资源:


推荐阅读