【问题标题】:spring boot testing - passing commandline arguments春季启动测试 - 传递命令行参数
【发布时间】:2015-05-15 22:56:52
【问题描述】:

我有带有注释的集成测试:

@WebAppConfiguration
@ActiveProfiles("integration")
@ContextConfiguration(loader = SpringApplicationContextLoader, classes = [MyApplication])
@IntegrationTest(["server.port=0"])

我可以传递例如 server.port 属性来测试上下文,但是有没有办法传递命令行参数?我的应用程序正常启动是这样的:

public static final void main(String[] args) {
    SpringApplication.run(AnkaraCollectorApplication.class, args);
}

我想传递一些参数来测试上下文。这个有什么属性吗?

【问题讨论】:

    标签: java spring spring-boot spring-test


    【解决方案1】:

    如果您使用的是 maven,您可以在故障安全插件中传递测试 JVM 参数:

    <plugin> <artifactId>maven-failsafe-plugin</artifactId> <executions> <execution> ... <configuration>
    <argLine> whatever you want: -DhelloWorld=Test </argLine> </configuration> ...

    您还可以根据您正在执行的 Maven 配置文件设置此 JVM 参数:

    <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <!-- Development JVM arguments --> <test-arguments>-Dhello=true</test-arguments> <!-- Default environment --> <environment>develop</environment> </properties> </profile> ... <plugin> <artifactId>maven-failsafe-plugin</artifactId> <executions> <execution> ... <configuration>
    <argLine>${test-arguments}</argLine> </configuration> ...

    【讨论】:

    • 但我需要传递命令行参数。我使用了一些包含 spring ApplicationListener 的库,并且该侦听器使用来自 ApplicationEnvironmentPreparedEvent.getArgs() 的命令行参数。我必须做一些 getArgs() 将返回我的论点的事情。
    • 这里的问题是集成测试没有调用你的 Application.main 方法。它只是检查注释。你在哪里使用这些命令参数?
    【解决方案2】:

    尝试在测试类中设置:

    static {
        System.setProperty("key", "value");
    }
    

    【讨论】:

      【解决方案3】:

      在春季 2X 中使用:

      mvn clean install -Darg1=val1 -Darg2=val2
      

      在使用@Value 属性注入时,您永远不会得到“无法解析占位符”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-13
        • 1970-01-01
        • 2016-03-03
        • 1970-01-01
        • 2017-09-25
        • 1970-01-01
        • 1970-01-01
        • 2018-01-21
        相关资源
        最近更新 更多