Prev |  | Next

## 4.4. Basic unit testing

The basic pattern of unit testing with Neo4j is illustrated by the following example.

To access the Neo4j testing facilities you should have the `neo4j-kernel` tests.jar on the classpath during tests. You can download it from Maven Central: org.neo4j:neo4j-kernel.

Using Maven as a dependency manager you would typically add this dependency as:

Maven dependency.

    <project>
    ...
     <dependencies>
      <dependency>
       <groupId>org.neo4j</groupId>
       <artifactId>neo4j-kernel</artifactId>
       <version>${neo4j-version}</version>
       <type>test-jar</type>
       <scope>test</scope>
      </dependency>
      ...
     </dependencies>
    ...
    </project>

Where `${neo4j-version}` is the desired version of Neo4j.

With that in place, we’re ready to code our tests.

| Tip
For the full source code of this example see: Neo4jBasicTest.java

Before each test, create a fresh database:

    @Before
    public void prepareTestDatabase()
    {
        graphDb = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase();
    }

After the test has executed, the database should be shut down:

    @After
    public void destroyTestDatabase()
    {
        graphDb.shutdown();
    }

During a test, create nodes and check to see that they are there, while enclosing 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" ) );

If you want to set configuration parameters at database creation, it’s done like this:

    Map<String, String> config = new HashMap<String, String>();
    config.put( "neostore.nodestore.db.mapped_memory", "10M" );
    config.put( "string_block_size", "60" );
    config.put( "array_block_size", "300" );
    GraphDatabaseService db = new ImpermanentGraphDatabase( config );

Copyright © 2013 Neo Technology

Prev | Up | Next
| Home |