使用 Spring 启动的 Kotlin 集成测试

Kotlin integration Tests with Spring Boot

我有什么:我正在开发一个微服务,使用 Spring 使用 Web 启动和 MongoDB 作为存储。对于 CI 集成测试,我使用测试容器。我有两个带有 SpringBootTest 注释的集成测试,它们使用 TestConfig class。 TestConfig class 提供带有固定暴露端口的设置 MongoDB 测试容器。

我的问题:当我 运行 我一次测试一个时,它们就会成功。但是当我同时 运行 我的测试时,它们就失败了。

MongoContainerConfig.kt

@TestConfiguration
class MongoContainerConfig {

    var mongoContainer: GenericContainer<Nothing>

    constructor() {
        mongoContainer = FixedHostPortGenericContainer<Nothing>("mongo")
                .withFixedExposedPort(27018,27017)
        mongoContainer.start()
    }

    @PreDestroy
    fun close() {
        mongoContainer.stop()
    }
}

初试

@SpringBootTest(
    classes = arrayOf(MongoContainerConfig::class, AssertUtilsConfig::class),
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
class CardControllerTest {

    @Test
    fun test() {}
}

第二次测试

@SpringBootTest(classes = arrayOf(MongoContainerConfig::class, AssertUtilsConfig::class))
class PositiveTest {

    @Test
    fun test() {}
}

错误消息

Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoContainerConfig': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.lang.card.engcard.config.MongoContainerConfig$$EnhancerBySpringCGLIB$$e58ffeee]: Constructor threw exception; nested exception is org.testcontainers.containers.ContainerLaunchException: Container startup failed
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1320)
    a

您可以在 github 和 CI 上看到这个项目 https://github.com/GSkoba/eng-card/runs/576320155?check_suite_focus=true

这很有趣,因为如果将它们重写为 java

,测试就会起作用

哈,不容易) https://docs.spring.io/spring/docs/5.2.5.RELEASE/spring-framework-reference/testing.html#testcontext-ctx-management-caching 测试具有不同的上下文,这也是 MongoContainerConfig 调用两次的原因。 修复 - 添加 webEnv CardControllerTest.kt

@SpringBootTest(classes = arrayOf(MongoContainerConfig::class, AssertUtilsConfig::class),
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PositiveTest 

证明https://github.com/GSkoba/eng-card/actions/runs/78094215