Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,23 @@ void withSharding() {
setEntrypoint("sh");
}
}

/**
* Executes a MongoDB initialization script from the classpath during startup.
* <p>
* The script will be copied to {@code /docker-entrypoint-initdb.d/init.js}.
* This method also adjusts the {@link org.testcontainers.containers.wait.strategy.WaitStrategy}
* to expect the "waiting for connections" log message twice, as the execution of an init script
* causes MongoDB to restart.
*
* @param scriptPath the path to the init script file on the classpath
* @return this container instance
*/
public MongoDBContainer withInitScript(String scriptPath) {
withCopyFileToContainer(MountableFile.forClasspathResource(scriptPath), "/docker-entrypoint-initdb.d/init.js");

this.waitStrategy = Wait.forLogMessage("(?i).*waiting for connections.*", 2);

return this;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.testcontainers.containers;

import org.junit.jupiter.api.Test;

import java.time.Duration;

import static org.assertj.core.api.Assertions.assertThat;

class MongoDBInitScriptTest {

@Test
void testWithInitScript() {
// Start the container using try-with-resources to ensure it closes automatically
try (
MongoDBContainer mongoDB = new MongoDBContainer("mongo:4.0.10")
// Configure the init script. This triggers a restart inside the container,
// so the container must wait for the second "waiting for connections" log message.
.withInitScript("init.js")
.withStartupTimeout(Duration.ofSeconds(30))
) {
mongoDB.start();

// Assert that the container started successfully
assertThat(mongoDB.isRunning()).isTrue();
}
}
}
1 change: 1 addition & 0 deletions modules/mongodb/src/test/resources/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
db.createCollection("test_collection");