SpringBoot + JUnit5 + Neo4j

Categories: devenv, java, neo4j, testing

There is no question that running any database in memory, during your unit test may not be the best approach. In general, using a method like TestContainers is a better approach to this problem.

The only issue when we use such an approach is that we need a docker environment to run this procedure, which currently I don’t have available while building in on the CI server.

With Neo4J it is possible to the database embedded in the memory, which has its own problems, but in general, it also works.

In this article, I will present how to setup the test using SpringBoot, JUnit5, and Gradle. If you are looking for a more in-depth article about Testing your Neo4j application, I would recommend this article from Michael Simons: Testing your Neo4j-based Java application.

The first thing to use an embedded Neo4j inside of your unit test is to add the neo4j-harness dependency to your project.

The second thing is to add @ExtendedWith(Ne4jExtension.class) to you unit testing class. This is all that is necessary to have the embedded Neo4j started, but such instant is started in a Random port, so we need to grab it and use such port on Spring configuration.

To get that we can use a @BeforeAll annotated method that collects the embedded neo4j instant:

/**
 * Reference to the testing Neo4J created, can be used to extract the
 * boltURI, that can be used as
 * input for the driver.
 */
public static Neo4j NEO4J_LOCAL;

//...

@BeforeAll
public static void loadNeoj4Driver(Neo4j neo4j) {
  NEO4J_LOCAL = neo4j;
}

This will be a static instance, so we can reference it on a configuration class for spring data. Although you can create a log of the inner objects, the only thing that you really need to create is an instance of org.neo4j.driver.Driver. That can be done using a configuration class:

/**
 * Configuration class used to create the {@link Driver} using the boltURI
 * extract from the internal Neo4j 
 * ({@link DemoApplicationTests#NEO4J_LOCAL}).
 */
@Configuration
public static class Neo4jTestConfiguration {

  /**
   * Neo4j properties load by spring, used to extract the configuration to
   * create a proper driver.
   */
  @Autowired Neo4jDriverProperties driverProperties;

  @Bean
  public Driver configuration() {
    return GraphDatabase.driver(NEO4J_LOCAL.boltURI(), driverProperties.asDriverConfig());
  }
}

As you can see we use the initiated NEO4J_LOCAL to extract the boltURI (the only thing that we need from the embedded neo4j), the rest we use the Spring auto-configuration to collect, this is internally done through the Neo4jDriverProperties#asDriverConfig method.

Here is the highlight of a way that you can make this integration works, you find a full working example here: https://github.com/laerteocj/demo-spring-neo4j-junit.

«

    Leave a Reply

    Your email address will not be published. Required fields are marked *