Neo4j のテスト

Neo4j Wiki から

When it comes to testing your interaction to the graph database there are several means of supporting it.

Testing against a datastore is always tricky because of:

  • shared context of the tests,
  • effort to set up the test data set
  • cleaning up before the tests

目次

[edit] Things to keep in mind

  • wrap modification operations in transactions
  • cleanly shutdown the db after your test
  • try to do unit tests of your app without a datastore whenever possible that will speed things

[edit] Use the ImpermanentGraphDatabase

This decorator around EmbeddedGraphDatabase cleans up at startup and shutdown, so you have a clean db for each test run. You can use it with a store dir but don't have to, it will create a temporary one instead.

Use it with this maven dependency

<dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j-kernel</artifactId>
  <version>1.3-SNAPSHOT</version>
  <classifier>tests</classifier>
  <scope>test</scope>
</dependency>
GraphDatabaseService gds = new org.neo4j.kernel.ImpermanentGraphDatabase();

[edit] Use rolled back transactions

When doing unit tests with a transactional context, and you don't care about committing the changes, rolling back the transaction instead of committing them gets rid of all your changes and leaves the datastore in a clean state Note that you wont test commit constraints that way. e.g

public class TestBase
{
    GraphDatabaseService gds = new EmbeddedGraphDatabaseService("target/test-db");
    Transaction tx;

    @Before public void startTransaction()
    {
        tx = gds.beginTx();
    } 
    
    @After public void rollBackAfterTests()
    {
        tx.failure();
        tx.finish();
        gds.shutdown();
    }
}

Spring Testcases do this automatically if you annotate the test-class or the test methods with @Transactional


[edit] Inspecting the Graph Database after a (failing) test

So if you didn't clean the db after the test you might want to inspect it. For that either the neo4j-shell (which comes with the neo4j-server) comes handy.

  neo4j-server/bin/neo4j-shell -p <path-to-db> [-readonly]

If the database was started with enableRemoteShell then you can also connect to the db while running your test (e.g. when being in a breakpoint)

-host      Domain name or IP of host to connect to (default: localhost)
-port      Port of host to connect to (default: 1337)
-name      RMI name, i.e. rmi://<host>:<port>/<name> (default: shell)
-pid       Process ID to connect to
-c         Command line to execute. After executing it the shell exits
-readonly  Connect in readonly mode
-path      Points to a neo4j db path so that a local server can be started there
-config    Points to a config file when starting a local server

You can also use Neoclipse to visualize your database.

When you're running against the Neo4j-(REST-)Server you can use the Webadmin UI to inspect the data.

Neo4j のサイト
ツールボックス