The basic pattern of unit testing with Neo4j is illustrated by the Neo4jBasicTest.java test.
Before each test, create a fresh database, deleting any pre-existing files:
deleteFileOrDirectory( testDatabasePath ); graphDb = new EmbeddedGraphDatabase( testDatabasePath.getAbsolutePath() );
File cleanup could happen here instead, but that would miss the opporunity to inspect the database after a test run. Instead, just shutdown the database:
graphDb.shutdown();
During a test, create nodes and check to see that they are there, being careful to enclose write operations in a transaction.
Transaction tx = graphDb.beginTx(); Node n = null; try { n = graphDb.createNode(); n.setProperty( "name", "Nancy" ); tx.success(); } catch ( Exception e ) { tx.failure(); } finally { tx.finish(); } // The node should have an id greater than 0, which is the id of the reference node. assertThat( n.getId(), is( greaterThan( 0l ) ) ); // Retrieve a node by using the id of the created node. The id's and property should match. Node foundNode = graphDb.getNodeById( n.getId() ); assertThat( foundNode.getId(), is( n.getId() ) ); assertThat( (String) foundNode.getProperty( "name" ), is( "Nancy" ) );
Full source code: Neo4jBasicTest