【问题标题】:Inject / override a properties value to a Spring Boot properties file in unit/integration tests phase在单元/集成测试阶段向 Spring Boot 属性文件注入/覆盖属性值
【发布时间】:2018-11-26 09:42:28
【问题描述】:

使用 Spring Boot 和 Testcontainers 我需要一种方法来动态地告诉应用程序测试容器正在侦听的端口是什么。

我知道在测试期间我可以告诉 Spring 使用不同的属性文件:

@TestPropertySource(locations = "classpath:application-integrationtests.yml")

但由于端口是随机的,我需要以编程方式将值注入 Spring 或属性文件。

我不是在谈论 @Value 参数,因为它会从属性文件中向 bean 注入一个值,因为当应用程序处于测试阶段时,无法知道该值是什么。

【问题讨论】:

标签: java unit-testing spring-boot integration-testing


【解决方案1】:

按照@Dirk Deyne 到an example from testcontainers demo 的极好链接,我在这里添加了Testcontainer 对上述问题的解决方案的副本(稍作修改):

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class,webEnvironment = 
                           WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = MyIntegrationTest.Initializer.class)
public class MyIntegrationTest {

public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        TestPropertyValues values = TestPropertyValues.of(
                "some.value.1=" + someObject.getSomeValue(),
                "some.value.2=" + someObject.getOtherValue()
        );
        values.applyTo(configurableApplicationContext);
    }
  }
}

【讨论】:

    【解决方案2】:

    可能有更好的方法,但我只是为此使用系统属性。

    @SpringBootTest
    @DirtiesContext
    public class MyTest {
        @BeforeClass
        public static void setUpEnvironment() {
            System.setProperty("kafka.bootstrap.servers", testKafka.getServers(); 
        }
        ...
    }
    

    【讨论】:

      【解决方案3】:

      很难写出正确的答案,因为您没有在使用 Testcontainers 的地方显示代码。但是from the documentation

      类规则提供了用于发现测试如何与容器交互的方法:

      getContainerIpAddress()返回容器监听的IP地址 getMappedPort(...) 返回容器上暴露的端口的 Docker 映射端口

      例如,对于上面的 Redis 示例,以下内容将允许您的测试访问 Redis 服务:

      String redisUrl = redis.getContainerIpAddress() + ":" + redis.getMappedPort(6379);

      所以您应该能够轻松访问这些信息。

      【讨论】:

        猜你喜欢
        • 2018-07-12
        • 2019-03-20
        • 1970-01-01
        • 2016-08-07
        • 2014-12-25
        • 2017-07-12
        • 2015-12-26
        • 1970-01-01
        • 2013-07-19
        相关资源
        最近更新 更多