I am able to start the mongo image, insert and read data just fine using the snippet below. Similar to the redis example on testcontainers.org.
private static final int MONGO_PORT = 27017;
@ClassRule
public static MongoDBContainer mongo = new MongoDBContainer("mongo:3.2.4")
.withExposedPorts(MONGO_PORT);
By default mongo doesn’t have credentials but I’m looking for a way to set the credentials so that my app’s MongoClient can get user/password from system properties and connect properly. I’ve tried adding the root user/password with the below but that didn’t set the credentials properly.
@ClassRule
public static MongoDBContainer mongo = new MongoDBContainer("mongo:3.2.4")
.withExposedPorts(MONGO_PORT)
.withEnv("MONGO_INITDB_ROOT_USERNAME", "admin")
.withEnv("MONGO_INITDB_ROOT_PASSWORD", "admin");
My question is: How can I start the test container with a username and password to allow my app to connect to it during my integration test using wiremock.
2
Answers
Checking the docs you can have a
GenericContainer
rather than specifically aMongoDbContainer
(not certain this makes much difference given it looks largely like I’ve got the same as what you’ve already tried)…I’ve then run:
the logs from the container show:
docker logs [container_id]
:I can login successfully inside the container with my new administrative user:
In short, you can find working example of test with MongoDB container here.
To provide, more details: you can configure authentication to MongoDB test container by using
GenericContainer
and setting environment with following propertiesMONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD
:Then you should use
MongoClient
with correspondingMongoCredential
. For example, below is the test, that writes and reads document to/from MongoDB container.Notes:
To find more details on environment variables, you check documentation here (specifically, Environment Variables section)
To find more details on authenticated connection to MongoDB, you check documentation here