POSTS

Unit Testing a Neo4j Model

I have jumped the nosql-train and have been using neo4j in a couple of projects recently. I like the idea that the data model is a graph. It feels like less of an impedance mismatch than between classes and relational tables (JPA/ORM).

Creating a model for an application with POJOs and neo4j is pretty straightforward to do in a good way (just check out the neo4j Design Guide on their wiki). It does require some coding wrapping/unwrapping nodes though. As with any other production code you would want test coverage for that code.

Here is one possible solution for unittesting that neo4j-specific model code (in a maven project): create a test fixture that sets up a neo4j-database under target/ so that it is removed on mvn clean and avoid commiting the transaction so that we avoid ever actually writing anything on disk (to avoid a performance hit on the unit tests).

Sample Junit 4.8 test base class implementation:

public abstract class Neo4jTestFixture {
    private static GraphDatabaseService databaseService;
    private Transaction tx;
    @BeforeClass
    public static void createDatabase() {
       databaseService = new EmbeddedGraphDatabase("target/test-db");
    }
    @Before
    public void startTransaction() {
        tx = databaseService.beginTx();
    }
    protected static GraphDatabaseService getDatabaseService() {
        return databaseService;
    }
    @After
    public void rollbackAfterTests() {
        tx.failure();
        tx.finish();
    }
    @AfterClass
    public static void tearDownDatabase() {
        databaseService.shutdown();
    }
}