MongoDB module for Testcontainers that provides lightweight, throwaway instances of MongoDB databases for testing.
npx @tessl/cli install tessl/maven-org-testcontainers--mongodb@1.21.00
# Testcontainers MongoDB Module
1
2
The Testcontainers MongoDB module provides lightweight, throwaway instances of MongoDB databases for testing. It includes two container types: MongoDBContainer for standard MongoDB database testing with automatic replica set initialization, and MongoDBAtlasLocalContainer for MongoDB with Atlas Search and Vector Search capabilities.
3
4
## Package Information
5
6
- **Package Name**: org.testcontainers:mongodb
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**: Add to your Maven dependencies:
10
11
```xml
12
<dependency>
13
<groupId>org.testcontainers</groupId>
14
<artifactId>mongodb</artifactId>
15
<version>1.21.3</version>
16
</dependency>
17
```
18
19
For Gradle:
20
21
```groovy
22
testImplementation 'org.testcontainers:mongodb:1.21.3'
23
```
24
25
## Core Imports
26
27
```java
28
import org.testcontainers.containers.MongoDBContainer;
29
import org.testcontainers.mongodb.MongoDBAtlasLocalContainer;
30
```
31
32
## Basic Usage
33
34
### Standard MongoDB Container
35
36
```java
37
import org.testcontainers.containers.MongoDBContainer;
38
39
// Create and start a MongoDB container
40
try (MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:7.0")) {
41
mongoDBContainer.start();
42
43
// Get connection string for your tests
44
String connectionString = mongoDBContainer.getConnectionString();
45
46
// Or get a replica set URL for a specific database
47
String replicaSetUrl = mongoDBContainer.getReplicaSetUrl("myTestDatabase");
48
49
// Use the connection string in your MongoDB client
50
// MongoClient client = MongoClients.create(connectionString);
51
}
52
```
53
54
### MongoDB Atlas Local Container
55
56
```java
57
import org.testcontainers.mongodb.MongoDBAtlasLocalContainer;
58
59
// Create and start a MongoDB Atlas Local container with search capabilities
60
try (MongoDBAtlasLocalContainer container = new MongoDBAtlasLocalContainer("mongodb/mongodb-atlas-local:7.0.9")) {
61
container.start();
62
63
// Get connection string
64
String connectionString = container.getConnectionString();
65
66
// Or get database-specific connection string
67
String dbConnectionString = container.getDatabaseConnectionString("mySearchDatabase");
68
}
69
```
70
71
## Capabilities
72
73
### Standard MongoDB Container
74
75
The `MongoDBContainer` class provides a MongoDB database instance with automatic replica set initialization to support multi-document transactions.
76
77
```java { .api }
78
public class MongoDBContainer extends GenericContainer<MongoDBContainer> {
79
80
// Constructors
81
@Deprecated
82
public MongoDBContainer();
83
public MongoDBContainer(String dockerImageName);
84
public MongoDBContainer(DockerImageName dockerImageName);
85
86
// Connection methods
87
public String getConnectionString();
88
public String getReplicaSetUrl();
89
public String getReplicaSetUrl(String databaseName);
90
91
// Configuration methods
92
public MongoDBContainer withSharding();
93
}
94
```
95
96
**Supported Images**:
97
- `mongo` (official MongoDB image)
98
- `mongodb/mongodb-community-server`
99
- `mongodb/mongodb-enterprise-server`
100
101
**Exposed Ports**: 27017
102
103
#### Connection Methods
104
105
- `getConnectionString()`: Returns a MongoDB connection URL without database reference
106
- `getReplicaSetUrl()`: Returns a replica set URL for the default "test" database
107
- `getReplicaSetUrl(String databaseName)`: Returns a replica set URL for the specified database
108
109
#### Configuration Methods
110
111
- `withSharding()`: Enables sharding on the MongoDB cluster. Returns the container instance for method chaining.
112
113
#### Usage Example with Sharding
114
115
```java
116
try (MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:7.0")
117
.withSharding()) {
118
mongoDBContainer.start();
119
120
String connectionString = mongoDBContainer.getConnectionString();
121
// Container now runs with sharding enabled
122
}
123
```
124
125
### MongoDB Atlas Local Container
126
127
The `MongoDBAtlasLocalContainer` class provides a MongoDB Atlas Local instance with search and vector search capabilities.
128
129
```java { .api }
130
public class MongoDBAtlasLocalContainer extends GenericContainer<MongoDBAtlasLocalContainer> {
131
132
// Constructors
133
public MongoDBAtlasLocalContainer(String dockerImageName);
134
public MongoDBAtlasLocalContainer(DockerImageName dockerImageName);
135
136
// Connection methods
137
public String getConnectionString();
138
public String getDatabaseConnectionString();
139
public String getDatabaseConnectionString(String databaseName);
140
}
141
```
142
143
**Supported Images**: `mongodb/mongodb-atlas-local`
144
145
**Exposed Ports**: 27017
146
147
#### Connection Methods
148
149
- `getConnectionString()`: Returns a MongoDB connection URL with `directConnection=true` parameter
150
- `getDatabaseConnectionString()`: Returns a database-specific connection string for the default "test" database
151
- `getDatabaseConnectionString(String databaseName)`: Returns a database-specific connection string for the specified database
152
153
### Inherited Container Functionality
154
155
Both container classes inherit extensive functionality from Testcontainers' `GenericContainer`, including:
156
157
#### Container Lifecycle
158
159
```java { .api }
160
// Container lifecycle methods
161
public void start();
162
public void stop();
163
public void close(); // AutoCloseable interface
164
public boolean isRunning();
165
```
166
167
#### Network and Port Access
168
169
```java { .api }
170
// Network access methods
171
public String getHost();
172
public Integer getMappedPort(int originalPort);
173
public Integer getFirstMappedPort();
174
```
175
176
#### Container Configuration
177
178
```java { .api }
179
// Configuration methods (fluent interface - return this)
180
public SELF withExposedPorts(Integer... ports);
181
public SELF withEnv(String key, String value);
182
public SELF withCommand(String... commandParts);
183
public SELF withLogConsumer(Consumer<OutputFrame> logConsumer);
184
```
185
186
#### File Operations
187
188
```java { .api }
189
// File transfer methods
190
public void copyFileToContainer(MountableFile mountableFile, String containerPath);
191
public void copyFileFromContainer(String containerPath, String destinationPath);
192
193
// Command execution
194
public Container.ExecResult execInContainer(String... command)
195
throws UnsupportedOperationException, IOException, InterruptedException;
196
```
197
198
## Types
199
200
### Core Types
201
202
```java { .api }
203
// From Testcontainers core
204
class DockerImageName {
205
public static DockerImageName parse(String fullImageName);
206
public DockerImageName withTag(String tag);
207
}
208
209
// MongoDB-specific exception
210
class MongoDBContainer.ReplicaSetInitializationException extends RuntimeException {
211
// Thrown when replica set initialization fails
212
}
213
214
// Container execution result
215
interface Container.ExecResult {
216
int getExitCode();
217
String getStdout();
218
String getStderr();
219
}
220
```
221
222
### Generic Container Types
223
224
```java { .api }
225
// Log output consumer
226
interface Consumer<OutputFrame> {
227
void accept(OutputFrame frame);
228
}
229
230
// File transfer
231
class MountableFile {
232
public static MountableFile forClasspathResource(String resourcePath);
233
public static MountableFile forHostPath(String path);
234
}
235
```
236
237
## Error Handling
238
239
### Replica Set Initialization
240
241
The `MongoDBContainer` may throw a `ReplicaSetInitializationException` if replica set initialization fails:
242
243
```java
244
try (MongoDBContainer container = new MongoDBContainer("mongo:7.0")) {
245
container.start(); // May throw ReplicaSetInitializationException
246
} catch (MongoDBContainer.ReplicaSetInitializationException e) {
247
// Handle replica set initialization failure
248
System.err.println("Failed to initialize replica set: " + e.getMessage());
249
}
250
```
251
252
### Container State Validation
253
254
Connection string methods validate container state:
255
256
```java
257
try (MongoDBContainer container = new MongoDBContainer("mongo:7.0")) {
258
// This will throw IllegalStateException - container not started yet
259
String url = container.getReplicaSetUrl("mydb");
260
} catch (IllegalStateException e) {
261
System.err.println("Container must be started first");
262
}
263
```
264
265
## Testing Patterns
266
267
### Try-with-resources Pattern
268
269
Both containers implement `AutoCloseable` for automatic cleanup:
270
271
```java
272
@Test
273
public void testMongoDBOperations() {
274
try (MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:7.0")) {
275
mongoDBContainer.start();
276
277
// Your test code here
278
String connectionString = mongoDBContainer.getConnectionString();
279
// Container automatically stopped and cleaned up
280
}
281
}
282
```
283
284
### JUnit Integration
285
286
Containers work seamlessly with JUnit and other testing frameworks:
287
288
```java
289
class MongoDBIntegrationTest {
290
291
@Test
292
void shouldExecuteTransactions() {
293
try (MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:7.0")) {
294
mongoDBContainer.start();
295
296
// Test multi-document transactions using replica set URL
297
String replicaSetUrl = mongoDBContainer.getReplicaSetUrl();
298
// Execute your transaction test logic
299
}
300
}
301
302
@Test
303
void shouldPerformAtlasSearchOperations() {
304
try (MongoDBAtlasLocalContainer container =
305
new MongoDBAtlasLocalContainer("mongodb/mongodb-atlas-local:7.0.9")) {
306
container.start();
307
308
// Test Atlas search and vector search functionality
309
String connectionString = container.getDatabaseConnectionString("searchdb");
310
// Execute your search test logic
311
}
312
}
313
}
314
```