0
# Neo4j Testcontainers
1
2
A Java library module providing lightweight, throwaway Neo4j graph database instances for testing. The Neo4j Testcontainers module integrates with JUnit to create isolated Neo4j database containers that start automatically for tests and clean up afterward, supporting both Community and Enterprise editions.
3
4
## Package Information
5
6
- **Package Name**: org.testcontainers:neo4j
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**: Add to `pom.xml`:
10
```xml
11
<dependency>
12
<groupId>org.testcontainers</groupId>
13
<artifactId>neo4j</artifactId>
14
<version>1.21.3</version>
15
<scope>test</scope>
16
</dependency>
17
```
18
19
For Gradle:
20
```gradle
21
testImplementation 'org.testcontainers:neo4j:1.21.3'
22
```
23
24
## Core Imports
25
26
```java
27
import org.testcontainers.containers.Neo4jContainer;
28
import org.testcontainers.containers.Neo4jLabsPlugin;
29
import org.testcontainers.utility.DockerImageName;
30
import org.testcontainers.utility.MountableFile;
31
import org.testcontainers.containers.wait.strategy.WaitStrategy;
32
```
33
34
## Basic Usage
35
36
```java
37
import org.testcontainers.containers.Neo4jContainer;
38
import org.neo4j.driver.AuthTokens;
39
import org.neo4j.driver.Driver;
40
import org.neo4j.driver.GraphDatabase;
41
import org.neo4j.driver.Result;
42
import org.neo4j.driver.Session;
43
44
public class Neo4jTest {
45
46
@Test
47
public void testWithNeo4j() {
48
try (Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4")) {
49
neo4jContainer.start();
50
51
// Get connection details
52
String boltUrl = neo4jContainer.getBoltUrl();
53
String password = neo4jContainer.getAdminPassword();
54
55
// Connect and run query
56
try (Driver driver = GraphDatabase.driver(boltUrl, AuthTokens.basic("neo4j", password));
57
Session session = driver.session()) {
58
59
session.run("CREATE (n:Person {name: 'Test'})");
60
Result result = session.run("MATCH (n:Person) RETURN n.name AS name");
61
// Process results...
62
}
63
}
64
}
65
}
66
```
67
68
## Architecture
69
70
The Neo4j Testcontainers module follows the standard Testcontainers architecture:
71
72
- **Neo4jContainer**: Main container class extending GenericContainer with Neo4j-specific functionality
73
- **Configuration Methods**: Fluent API for setting up authentication, plugins, and Neo4j-specific options
74
- **Connection Access**: Methods to get Bolt, HTTP, and HTTPS endpoints for various client types
75
- **Docker Integration**: Automatic image management, port mapping, and lifecycle control
76
77
## Capabilities
78
79
### Container Creation and Configuration
80
81
Create and configure Neo4j container instances with various Docker images and settings.
82
83
```java { .api }
84
/**
85
* Testcontainers implementation for Neo4j.
86
* Supported image: neo4j
87
* Exposed ports: Bolt (7687), HTTP (7474), HTTPS (7473)
88
*
89
* @param <S> Self-type for method chaining
90
*/
91
public class Neo4jContainer<S extends Neo4jContainer<S>> extends GenericContainer<S> {
92
93
/**
94
* Creates a Neo4jContainer using the official Neo4j docker image.
95
* @deprecated use Neo4jContainer(DockerImageName) instead
96
*/
97
@Deprecated
98
public Neo4jContainer();
99
100
/**
101
* Creates a Neo4jContainer using a specific docker image.
102
* @param dockerImageName The docker image to use
103
*/
104
public Neo4jContainer(String dockerImageName);
105
106
/**
107
* Creates a Neo4jContainer using a specific docker image.
108
* @param dockerImageName The docker image to use
109
*/
110
public Neo4jContainer(DockerImageName dockerImageName);
111
112
/**
113
* Configures the container to use the enterprise edition.
114
* Requires license acceptance.
115
* @return This container
116
*/
117
public S withEnterpriseEdition();
118
}
119
```
120
121
### Authentication Management
122
123
Configure Neo4j authentication settings including custom passwords, random passwords, or disabled authentication.
124
125
```java { .api }
126
/**
127
* Sets the admin password for the default account (neo4j).
128
* @param adminPassword The admin password (minimum 8 characters for Neo4j 5.3+)
129
* @return This container
130
*/
131
public S withAdminPassword(String adminPassword);
132
133
/**
134
* Disables authentication.
135
* @return This container
136
*/
137
public S withoutAuthentication();
138
139
/**
140
* Sets a random UUID-based password.
141
* @return This container
142
*/
143
public S withRandomPassword();
144
145
/**
146
* Gets the admin password for the neo4j account.
147
* @return The admin password or null if auth is disabled
148
*/
149
public String getAdminPassword();
150
```
151
152
**Usage Example:**
153
```java
154
// Custom password
155
Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:4.4")
156
.withAdminPassword("mySecretPassword");
157
158
// Disable authentication
159
Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:4.4")
160
.withoutAuthentication();
161
162
// Random UUID-based password
163
Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:4.4")
164
.withRandomPassword();
165
```
166
167
### Connection URL Access
168
169
Get connection URLs for different Neo4j protocols and endpoints.
170
171
```java { .api }
172
/**
173
* Gets the Bolt URL for use with Neo4j's Java-Driver.
174
* @return Bolt URL in format: bolt://host:port
175
*/
176
public String getBoltUrl();
177
178
/**
179
* Gets the URL of the transactional HTTP endpoint.
180
* @return HTTP URL in format: http://host:port
181
*/
182
public String getHttpUrl();
183
184
/**
185
* Gets the URL of the transactional HTTPS endpoint.
186
* @return HTTPS URL in format: https://host:port
187
*/
188
public String getHttpsUrl();
189
```
190
191
**Usage Example:**
192
```java
193
Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:4.4");
194
container.start();
195
196
// For Neo4j Java Driver (Bolt protocol)
197
String boltUrl = container.getBoltUrl();
198
Driver driver = GraphDatabase.driver(boltUrl, AuthTokens.basic("neo4j", "password"));
199
200
// For HTTP REST API
201
String httpUrl = container.getHttpUrl();
202
// Make HTTP requests to httpUrl + "/db/data/transaction/commit"
203
204
// For HTTPS REST API
205
String httpsUrl = container.getHttpsUrl();
206
```
207
208
### Database and Plugin Management
209
210
Add existing databases, custom plugins, and Neo4j Labs plugins to the container.
211
212
```java { .api }
213
/**
214
* Copies an existing graph.db folder into the container.
215
* Note: Only works with Neo4j 3.5.x
216
* @param graphDb The graph.db folder to copy
217
* @return This container
218
* @throws IllegalArgumentException If the database version is not 3.5
219
*/
220
public S withDatabase(MountableFile graphDb);
221
222
/**
223
* Adds plugins from a directory or file to the container.
224
* @param plugins Plugin directory or JAR file to copy
225
* @return This container
226
*/
227
public S withPlugins(MountableFile plugins);
228
229
/**
230
* Registers one or more Neo4j plugins for server startup.
231
* @param plugins Plugin names (e.g., "apoc", "graph-data-science")
232
* @return This container
233
*/
234
public S withPlugins(String... plugins);
235
236
/**
237
* Registers Neo4j Labs plugins using enum values.
238
* @param neo4jLabsPlugins Plugin enum values
239
* @return This container
240
* @deprecated Use withPlugins(String...) with plugin names instead
241
*/
242
@Deprecated
243
public S withLabsPlugins(Neo4jLabsPlugin... neo4jLabsPlugins);
244
245
/**
246
* Registers Neo4j Labs plugins using string names.
247
* @param neo4jLabsPlugins Plugin names
248
* @return This container
249
* @deprecated Use withPlugins(String...) instead
250
*/
251
@Deprecated
252
public S withLabsPlugins(String... neo4jLabsPlugins);
253
```
254
255
**Usage Example:**
256
```java
257
// Copy existing database (Neo4j 3.5 only)
258
Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:3.5.30")
259
.withDatabase(MountableFile.forClasspathResource("/test-graph.db"));
260
261
// Add custom plugins
262
Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:4.4")
263
.withPlugins(MountableFile.forClasspathResource("/custom-plugins"));
264
265
// Add Neo4j Labs plugins by name
266
Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:4.4")
267
.withPlugins("apoc", "graph-data-science");
268
```
269
270
### Neo4j Configuration
271
272
Set Neo4j-specific configuration options using the standard Neo4j configuration format.
273
274
```java { .api }
275
/**
276
* Adds Neo4j configuration properties to the container.
277
* Properties are automatically translated to the format required by the Neo4j container.
278
* @param key The configuration key (e.g., "dbms.security.procedures.unrestricted")
279
* @param value The configuration value
280
* @return This container
281
*/
282
public S withNeo4jConfig(String key, String value);
283
```
284
285
**Usage Example:**
286
```java
287
Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:4.4")
288
.withNeo4jConfig("dbms.security.procedures.unrestricted", "apoc.*,algo.*")
289
.withNeo4jConfig("dbms.tx_log.rotation.size", "42M")
290
.withNeo4jConfig("dbms.memory.heap.initial_size", "1G")
291
.withNeo4jConfig("dbms.memory.heap.max_size", "2G");
292
```
293
294
### Container Lifecycle and Information
295
296
Standard container lifecycle methods and information access inherited from GenericContainer.
297
298
```java { .api }
299
// Inherited lifecycle methods (from GenericContainer)
300
public void start();
301
public void stop();
302
public void restart();
303
public boolean isRunning();
304
305
/**
306
* Gets the ports used for liveness checks.
307
* @return Set of port numbers used for health checks
308
*/
309
public Set<Integer> getLivenessCheckPortNumbers();
310
311
// Inherited port and network information (from GenericContainer)
312
public Integer getMappedPort(int originalPort);
313
public String getHost();
314
315
/**
316
* Configures the container's internal settings.
317
* Called automatically during container startup.
318
*/
319
protected void configure();
320
```
321
322
## Types
323
324
### Neo4jLabsPlugin (Deprecated)
325
326
```java { .api }
327
/**
328
* Reflects a plugin from the official Neo4j 4.4.
329
* @deprecated Use withPlugins(String...) with matching plugin name for your Neo4j version
330
*/
331
@Deprecated
332
public enum Neo4jLabsPlugin {
333
APOC("apoc"),
334
APOC_CORE("apoc-core"),
335
BLOOM("bloom"),
336
STREAMS("streams"),
337
GRAPH_DATA_SCIENCE("graph-data-science"),
338
NEO_SEMANTICS("n10s");
339
340
final String pluginName;
341
342
Neo4jLabsPlugin(String pluginName);
343
}
344
```
345
346
### Constants
347
348
```java { .api }
349
/**
350
* Default wait strategy for Bolt protocol readiness.
351
* Waits for log message indicating Bolt is enabled on port 7687.
352
*/
353
public static final WaitStrategy WAIT_FOR_BOLT;
354
355
// Default ports (private constants, accessed via getMappedPort())
356
private static final int DEFAULT_BOLT_PORT = 7687;
357
private static final int DEFAULT_HTTP_PORT = 7474;
358
private static final int DEFAULT_HTTPS_PORT = 7473;
359
360
// Default configuration (private constants)
361
private static final String DEFAULT_ADMIN_PASSWORD = "password";
362
private static final String DEFAULT_TAG = "4.4";
363
private static final String ENTERPRISE_TAG = "4.4-enterprise";
364
private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("neo4j");
365
```
366
367
## Error Handling
368
369
Common exceptions and error scenarios:
370
371
- **IllegalArgumentException**: Thrown when trying to use `withDatabase()` with Neo4j 4.0+ (only supports 3.5.x)
372
- **IllegalStateException**: Thrown when trying to use Enterprise edition without accepting the license
373
- **ContainerLaunchException**: May be thrown if Neo4j container fails to start due to configuration issues
374
375
## Version Compatibility
376
377
- **Neo4j 3.5.x**: Supports database copying via `withDatabase()`
378
- **Neo4j 4.x**: Default version (4.4), supports all plugin features
379
- **Neo4j 5.x**: Requires minimum 8-character passwords
380
- **Enterprise Edition**: Requires license acceptance via environment variable or license file
381
382
## Examples
383
384
### JUnit 4 Integration
385
```java
386
public class Neo4jIntegrationTest {
387
@ClassRule
388
public static Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4");
389
390
@Test
391
public void testDatabaseQuery() {
392
try (Driver driver = GraphDatabase.driver(
393
neo4jContainer.getBoltUrl(),
394
AuthTokens.basic("neo4j", neo4jContainer.getAdminPassword()));
395
Session session = driver.session()) {
396
397
Result result = session.run("RETURN 1 AS number");
398
assertEquals(1L, result.single().get("number").asLong());
399
}
400
}
401
}
402
```
403
404
### JUnit 5 Integration
405
```java
406
@Testcontainers
407
class Neo4jTest {
408
@Container
409
static Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4")
410
.withAdminPassword("testPassword")
411
.withPlugins("apoc");
412
413
@Test
414
void testWithApocPlugin() {
415
try (Driver driver = GraphDatabase.driver(
416
neo4jContainer.getBoltUrl(),
417
AuthTokens.basic("neo4j", "testPassword"));
418
Session session = driver.session()) {
419
420
// Test APOC functionality
421
Result result = session.run("RETURN apoc.version() AS version");
422
assertNotNull(result.single().get("version").asString());
423
}
424
}
425
}
426
```