title: Kotlin integration Tests with Spring Boot
body: <p>What I have: I'm developing a microservice, using Spring Boot with Web and MongoDB as storage. For CI integration tests I use test containers. I have two integrations tests with SpringBootTest annotations, which use TestConfig class. TestConfig class provides setup MongoDB test container with fixed exposed ports. </p>
  
  <p>My problem: When I run my tests one at a time then they succeed. But when I run my tests at the same time then they failed.</p>
  
  <p><strong>MongoContainerConfig.kt</strong></p>
  
  <pre><code>@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()
      }
  }
  </code></pre>
  
  <p><strong>First test</strong> </p>
  
  <pre><code>@SpringBootTest(
      classes = arrayOf(MongoContainerConfig::class, AssertUtilsConfig::class),
      webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
  )
  class CardControllerTest {
  
      @Test
      fun test() {}
  }
  </code></pre>
  
  <p><strong>Second test</strong></p>
  
  <pre><code>@SpringBootTest(classes = arrayOf(MongoContainerConfig::class, AssertUtilsConfig::class))
  class PositiveTest {
  
      @Test
      fun test() {}
  }
  </code></pre>
  
  <p><strong>Error msg</strong> </p>
  
  <pre><code>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
  </code></pre>
  
  <p>This project you can see on github with CI 
  <a href="https://github.com/GSkoba/eng-card/runs/576320155?check_suite_focus=true" rel="nofollow noreferrer">https://github.com/GSkoba/eng-card/runs/576320155?check_suite_focus=true</a></p>
  
  <p>It's very funny because tests work if rewrite them to java</p>