Skip to content

Neo4j Module

This module helps to run Neo4j using Testcontainers.

Note that it's based on the official Docker image provided by Neo4j, Inc.

Even though the latest LTS version of Neo4j 4.4 is used in the examples of this documentation, the Testcontainers integration supports also newer 5.x images of Neo4j.

Usage example

Declare your Testcontainers as a @ClassRule or @Rule in a JUnit 4 test or as static or member attribute of a JUnit 5 test annotated with @Container as you would with other Testcontainers. You can either use call getBoltUrl() or getHttpUrl() on the Neo4j container. getBoltUrl() is meant to be used with one of the official Bolt drivers while getHttpUrl() gives you the HTTP-address of the transactional HTTP endpoint. On the JVM you would most likely use the Java driver.

The following example uses the JUnit 5 extension @Testcontainers and demonstrates both the usage of the Java Driver and the REST endpoint:

@Testcontainers
class Neo4jExampleTest {

    @Container
    private static Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>(DockerImageName.parse("neo4j:4.4"))
        .withoutAuthentication(); // Disable password

    @Test
    void testSomethingUsingBolt() {
        // Retrieve the Bolt URL from the container
        String boltUrl = neo4jContainer.getBoltUrl();
        try (Driver driver = GraphDatabase.driver(boltUrl, AuthTokens.none()); Session session = driver.session()) {
            long one = session.run("RETURN 1", Collections.emptyMap()).next().get(0).asLong();
            assertThat(one).isEqualTo(1L);
        } catch (Exception e) {
            fail(e.getMessage());
        }
    }

    @Test
    void testSomethingUsingHttp() throws IOException {
        // Retrieve the HTTP URL from the container
        String httpUrl = neo4jContainer.getHttpUrl();

        URL url = new URL(httpUrl + "/db/data/transaction/commit");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);

        try (Writer out = new OutputStreamWriter(con.getOutputStream())) {
            out.write("{\"statements\":[{\"statement\":\"RETURN 1\"}]}");
            out.flush();
        }

        assertThat(con.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK);
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String expectedResponse =
                "{\"results\":[{\"columns\":[\"1\"],\"data\":[{\"row\":[1],\"meta\":[null]}]}],\"errors\":[]}";
            String response = buffer.lines().collect(Collectors.joining("\n"));
            assertThat(response).isEqualTo(expectedResponse);
        }
    }
}

You are not limited to Unit tests, and you can use an instance of the Neo4j Testcontainers in vanilla Java code as well.

Additional features

Custom password

A custom password can be provided:

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4").withAdminPassword("verySecret");

Disable authentication

Authentication can be disabled:

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4")
    .withoutAuthentication()

Random password

A random (UUID-random based) password can be set:

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4").withRandomPassword();

Neo4j-Configuration

Neo4j's Docker image needs Neo4j configuration options in a dedicated format. The container takes care of that, and you can configure the database with standard options like the following:

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4")
    .withNeo4jConfig("dbms.security.procedures.unrestricted", "apoc.*,algo.*")
    .withNeo4jConfig("dbms.tx_log.rotation.size", "42M");

Add custom plugins

Custom plugins, like APOC, can be copied over to the container from any classpath or host resource like this:

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4")
    .withPlugins(MountableFile.forClasspathResource("/custom-plugins/hello-world.jar"))

Whole directories work as well:

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4")
    .withPlugins(MountableFile.forClasspathResource("/custom-plugins"))

Add Neo4j Docker Labs plugins

Add any Neo4j Labs plugin from the Neo4j 4.4 Docker Labs plugin list or Neo4j 5 plugin list.

Note

The methods withLabsPlugins(Neo4jLabsPlugin...) and withLabsPlugins(String... plugins) are deprecated. Please the method withPlugins(String... plugins).

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4") //
    .withPlugins("apoc", "bloom");

Start the container with a predefined database

If you have an existing database (graph.db) you want to work with, copy it over to the container like this:

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:3.5.30")
    .withDatabase(MountableFile.forClasspathResource("/test-graph.db"))

Note

The withDatabase method will only work with Neo4j 3.5 and throw an exception if used in combination with a newer version.

Choose your Neo4j license

If you need the Neo4j enterprise license, you can declare your Neo4j container like this:

Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.4")
    .withEnterpriseEdition()

This creates a Testcontainers based on the Docker image build with the Enterprise version of Neo4j 4.4. The call to withEnterpriseEdition adds the required environment variable that you accepted the terms and condition of the enterprise version. You accept those by adding a file named container-license-acceptance.txt to the root of your classpath containing the text neo4j:4.4-enterprise in one line.

If you are planning to run a newer Neo4j 5.x enterprise edition image, you have to manually define the proper enterprise image (e.g. neo4j:5-enterprise) and set the environment variable NEO4J_ACCEPT_LICENSE_AGREEMENT by adding .withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes") to your container definition.

You'll find more information about licensing Neo4j here: About Neo4j Licenses.

Adding this module to your project dependencies

Add the following dependency to your pom.xml/build.gradle file:

testImplementation "org.testcontainers:neo4j:1.19.7"
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>neo4j</artifactId>
    <version>1.19.7</version>
    <scope>test</scope>
</dependency>

Hint

Add the Neo4j Java driver if you plan to access the Testcontainers via Bolt:

compile "org.neo4j.driver:neo4j-java-driver:4.4.13"
<dependency>
    <groupId>org.neo4j.driver</groupId>
    <artifactId>neo4j-java-driver</artifactId>
    <version>4.4.13</version>
</dependency>