javaspring-boottestcontainers

How to define a TestConfiguration for TestContainers?


I have multiple test classes that use the mongo test container. Instead of declaring a container using the same code multiple times, I wanted to create a test configuration, to avoid repetitive code. Here is what I came up with

@TestConfiguration
@Testcontainers
public class MongoTestContainerConfig {

    @Container
    @ServiceConnection
    static final MongoDBContainer MONGO_CONTAINER = new MongoDBContainer("mongo:6.0");
}

However, when I try to run my tests, with this config

@DataMongoTest
@Import(MongoTestContainerConfig.class)
class ServiceRepositoryTest {

    @Autowired
    private MongoTemplate mongoTemplate;

It returns the following exception stack trace

[localhost:27017] [ ] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017 com.mongodb.MongoSocketOpenException: Exception opening socket Caused by: java.net.ConnectException: Connection refused

When I declare the test container inside of the test class, all works fine.

@Testcontainers
@DataMongoTest
class CspRepositoryTest {

    @Container
    @ServiceConnection
    private static final MongoDBContainer MONGO_CONTAINER = new MongoDBContainer("mongo:6.0");

Solution

  • declare the testcontainer as abstract class, which you extend by your acutal tests. something like this:

    @Testcontainers
    public abstract class MongoTestContainerConfig {
    
        @Container
        static final MongoDBContainer MONGO_CONTAINER = new MongoDBContainer("mongo:6.0");
    }
    
    
    @DataMongoTest
    class ServiceRepositoryTest extends MongoTestContainerConfig  {
    
            // access MONGO_CONTAINER from here
    }