Neo4j: unit testing the bolt driver properly

前端 未结 2 1482
南笙
南笙 2021-01-03 08:12

I am adding the Neo4j Bolt driver to my application just following the http://neo4j.com/developer/java/:

import org.neo4j.driver.v1.*;

Driver driver = Graph         


        
2条回答
  •  独厮守ぢ
    2021-01-03 08:51

    An easy way now is to pull neo4j-harness, and use their built-in Neo4jRule as follows:

    import static org.neo4j.graphdb.factory.GraphDatabaseSettings.boltConnector;
    // [...]
    @Rule public Neo4jRule graphDb = new Neo4jRule()
            .withConfig(boltConnector("0").address, "localhost:" + findFreePort());
    

    Where findFreePort implementation can be as simple as:

    private static int findFreePort() {
        try (ServerSocket socket = new ServerSocket(0)) {
            return socket.getLocalPort();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    

    As the Javadoc of ServerSocket explains:

    A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

    Moreover, the socket is closed before the port value is returned, so there are great chances the returned port will still be available upon return (the window of opportunity for the port to be allocated again in between is small - the computation of the window size is left as an exercise to the reader).

    Et voilà !

提交回复
热议问题