【问题标题】:SpringBootTest with Kotlin, TestContainers and External configuration带有 Kotlin、TestContainers 和外部配置的 SpringBootTest
【发布时间】:2020-12-14 05:06:38
【问题描述】:

我在为我的测试类创建外部配置时遇到问题。现在我的 redis 相关测试必须在里面有一个伴生对象

@Testcontainers
@TestPropertySource("classpath:/application-test.properties")
@SpringBootTest
class RedisRelatedTest {

  companion object {
    @Container
    val container = GenericContainer<Nothing>("redis:5.0.7-alpine")
            .apply { withExposedPorts(6379) }

    @JvmStatic
    @DynamicPropertySource
    fun properties(registry: DynamicPropertyRegistry) {
        registry.add("spring.redis.host", container::getHost);
        registry.add("spring.redis.port", container::getFirstMappedPort);
    }
  }
  ... some tesitng
}

我想把它移到外面的某个地方,并使用一些衬里来包含它,但我找不到可行的方法。我用它的伴生对象创建了一个 RedisConfig 类,但是 @Import(RedisConfig::class) 或 @Import(RedisConfig.Congig::class) 被完全忽略了。

【问题讨论】:

    标签: kotlin spring-boot-test testcontainers


    【解决方案1】:

    @Import(RedisConfig::class) 本身不做任何事情,你仍然需要自动装配一个 bean,你也这样做了吗?

    另一种选择是拥有一个带有容器的抽象类并在测试类中扩展它。

    【讨论】:

      【解决方案2】:

      @Import(RedisConfig::class) 不起作用。 如果是 @SpringTest 你应该使用:

      @SpringBootTest(
          classes = [RedisConfig::class])
      

      但我不确定 testcontainer 注释是否会按您的预期工作。我按照我在对类似问题的回复中描述的方式解决了这个问题:https://stackoverflow.com/a/66532851/3484423

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2014-10-15
        • 1970-01-01
        • 1970-01-01
        • 2019-05-09
        相关资源
        最近更新 更多