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: https://github.com/testcontainers/testcontainers-java/issues/4695
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:
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
- Create a very complicated test:
@SpringBootTest(classes = {TestApplication.class })
public class MongoDbConnectionTest {
@Autowired
private UserRepository userRepository;
@Test
@DisplayName("Make sure we're able to start connect to MongoDB")
void loadContext() {
var user = new User();
user.setName("Amazing user");
var savedUser = userRepository.save(user);
assertNotNull(savedUser);
}
}
- Add a test context:
@Configuration
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;
@Container
public static GenericContainer mongoDBContainer = new GenericContainer("mongo")
.withExposedPorts(MONGO_PORT)
.withEnv("MONGO_INITDB_ROOT_USERNAME", MONGO_USERNAME)
.withEnv("MONGO_INITDB_ROOT_PASSWORD", MONGO_PASSWORD)
.withEnv("MONGO_INITDB_DATABASE", MONGO_DATABASE);
static {
mongoDBContainer.start();
System.setProperty("spring.data.mongodb.uri", "mongodb://" + mongoDBContainer.getHost() + ":" + mongoDBContainer.getFirstMappedPort());
System.setProperty("spring.data.mongodb.username", MONGO_USERNAME);
System.setProperty("spring.data.mongodb.password", MONGO_PASSWORD);
System.setProperty("spring.data.mongodb.database", MONGO_DATABASE);
System.setProperty("spring.data.mongodb.authentication-database", MONGO_ADMINISTRATION_DATABASE);
}
}
And… That’s it. We have a started MongoDB container that has authentication. Good luck 🙂
Be First to Comment