What I have: there is a microservice on Spring boot, with web and MongoDB as a store. For integration tests, I am using test container. To test the microservice, 2 integration tests were written with SpringBootTest annotation and for them there is a TestConfig class for raising the mongodb container.
What is the problem: if you run tests one at a time, they pass, but if you run them at the same time, they fail.
MongoContainerConfig.kt
@ TestConfiguration
class MongoContainerConfig {
var mongoContainer: GenericContainer & lt; Nothing & gt;
constructor () {
mongoContainer = FixedHostPortGenericContainer & lt; Nothing & gt; ("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 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, then everything works)
Answer 1
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 therefore 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