Kotlin integration tests for spring-boot
What I have: there is a microservice on Spring boot, with the web and MongoDB as a storage. For integration tests, I use test container. For testing the microservice, 2 intagration tests with SpringBootTest annatation are written, and for them there is a TestConfig class for raising the mongodb container.
What is the problem: if you run the tests individually, they pass, but if you run them simultaneously, they fall. MongoContainerConfig.kt
@TestConfiguration
class MongoContainerConfig {
var mongoContainer: GenericContainer<Nothing>
constructor() {
mongoContainer = FixedHostPortGenericContainer<Nothing>("mongo")
.withFixedExposedPort(27018,27017)
mongoContainer.start()
}
@PreDestroy
fun close() {
mongoContainer.stop()
}
}
First test
@SpringBootTest(
classes = arrayOf(MongoContainerConfig::class, AssertUtilsConfig::class),
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
class CardControllerTest {
@Test
fun test() {}
}
Second test
@SpringBootTest(classes = arrayOf(MongoContainerConfig::class, AssertUtilsConfig::class))
class PositiveTest {
@Test
fun test() {}
}
Error msg
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
This project is available on github and this error can be viewed on CI https://github.com/GSkoba/eng-card/runs/576320155?check_suite_focus=true
The funny thing is that if you rewrite the tests and config in java, everything works)
1 answers
Haha, it wasn't easy) https://docs.spring.io/spring/docs/5.2.5.RELEASE/spring-framework-reference/testing.html#testcontext-ctx-management-caching The tests have different contexts and so MongoContainerConfig is called 2 times. Fix - add WebEnv to CardControllerTest.kt
@SpringBootTest(classes = arrayOf(MongoContainerConfig::class, AssertUtilsConfig::class),
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PositiveTest
Proof https://github.com/GSkoba/eng-card/actions/runs/78094215