How to run tests with authenticated Mongo TestContainers?

TestContainers is a great tool if you want to run integration tests and require a database. They even have support for MongoDB.

This MongoDB support works for simple use cases. But what if you want to run MongoDB with username and password? Unfortunately, it’s not that simple, as it appears there is a bug which does not allow to run MongoDB with authentication:

But with some magic, some help from the the issue above you can construct a Spring Boot test with authenticated MongoDB, TestContainers, jUnit and Spring Boot like so:

  • Create a simple fake main program in src/test/java directory:
public class TestApplication {

    public static void main(String[] args) {, args);

  • Create a very complicated test:
@SpringBootTest(classes = {TestApplication.class })
public class MongoDbConnectionTest {

    private UserRepository userRepository;

    @DisplayName("Make sure we're able to start connect to MongoDB")
    void loadContext() {
        var user = new User();
        user.setName("Amazing user");

        var savedUser =;

  • Add a test context:
public class MongoDBTestContainerConfig {

    private static final String MONGO_USERNAME = "test";
    private static final String MONGO_PASSWORD = "secret";
    private static final String MONGO_DATABASE = "database";
    private static final String MONGO_ADMINISTRATION_DATABASE = "admin";
    private static final int MONGO_PORT = 27017;

    public static GenericContainer mongoDBContainer = new GenericContainer("mongo")

    static {

        System.setProperty("", "mongodb://" + mongoDBContainer.getHost() + ":" + mongoDBContainer.getFirstMappedPort());
        System.setProperty("", MONGO_USERNAME);
        System.setProperty("", MONGO_PASSWORD);
        System.setProperty("", MONGO_DATABASE);
        System.setProperty("", MONGO_ADMINISTRATION_DATABASE);

And… That’s it. We have a started MongoDB container that has authentication. Good luck 🙂

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *