【问题标题】:How to pass profile while running mvn test for a springboot application如何在为 springboot 应用程序运行 mvn 测试时通过配置文件
【发布时间】:2020-09-15 14:50:43
【问题描述】:

我正在尝试运行 Spring Boot 应用程序的测试用例。
为此,我尝试使用mvn test -Dspring.profiles.active=test
但它没有用。
我需要在pom.xml中添加个人资料吗

你能帮忙吗?

【问题讨论】:

    标签: spring-boot maven


    【解决方案1】:

    java 参数位于 maven 生命周期参数之前:

    mvn -Dspring.profiles.active=test test
    

    您还可以将<argLine> 属性添加到maven surefire 插件以应用于所有测试。

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <systemPropertyVariables>
          <testEnvironment>true</testEnvironment>
        </systemPropertyVariables>
        <argLine>-Dspring.profiles.active=test</argLine>
      </configuration>
    </plugin>
    

    【讨论】:

      【解决方案2】:

      使用配置文件运行测试的最佳方法是使用 ActiveProfiles 注释(假设 JUnit 5):

      @SpringBootTest
      @ActiveProfiles("test")
      class MyApplicationTest {
      
        @Test
        void test() {
          // implement actual test here
        }
      }
      

      这将启动您的 Spring 应用程序并激活 test 配置文件。

      【讨论】:

      • 这里没有专门针对 JUnit 5 的任何东西。它也适用于其他测试库。
      • 好吧,如果你使用JUnit 4,你需要在类级别添加@RunWith(SpringRunner.class)。并且类和方法应该是公开的。
      • 啊。我的意思是专门使用 @ActiveProfiles 注释。它适用于任何测试框架。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 2022-01-22
      • 2021-09-08
      • 2018-12-20
      相关资源
      最近更新 更多