javacontainersquarkustestcontainersquarkus-testing

Quarkus always starts Testcontainers when running tests with @QuarkusTest, even if the test doesn't use Testcontainers


After configuring Testcontainers in my project, Quarkus keeps starting a container every time I run a test with @QuarkusTest, even if the test doesn't use Testcontainers.

My Testcontainers configuration:

@Testcontainers
public class MongoIntegrationTest {

  @Container
  public static final MongoDBContainer mongoDBContainer = new MongoDBContainer(
      DockerImageName.parse("mongo:4.2.3"))
      .withExposedPorts(27017);

  public static class Initializer implements QuarkusTestResourceLifecycleManager {

    @Override
    public Map<String, String> start() {
      MongoIntegrationTest.mongoDBContainer.start();
      // the way to dynamically expose allocated port
      return Maps.of("quarkus.mongodb.connection-string",
          "mongodb://" + mongoDBContainer.getHost() + ":"
              + mongoDBContainer.getMappedPort(27017));
    }

    @Override
    public void stop() {
      MongoIntegrationTest.mongoDBContainer.stop();
    }
  }

}

My test that requires Testcontainers, as it uses MongoDB:

@QuarkusTest
@QuarkusTestResource(MongoIntegrationTest.Initializer.class)
public class ClassMongoTest {

  @Test
  void test(){
    Assertions.assertTrue(true);
  }

}

But now, any class configured with @QuarkusTest is starting the MongoDB container...

@QuarkusTest
class ClassNormalTest {

  @Test
  void test(){
    Assertions.assertTrue(true);
  }

}

So, when I run my ClassNormalTest, Quarkus starts the containers...

Printscreen showing the Testcontainers containers:

Why? What do I need to do to fix this?


Solution

  • Use this on your test class:

    @QuarkusTestResource(value = MongoIntegrationTest.Initializer.class, restrictToAnnotatedClass = true)
    

    This will only startup Mongo on this test class.