The Neo4j Manual > Tutorials > Using Neo4j embedded in Java applications > Basic unit testing
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 together with JUnit and Hamcrest like so:

Maven dependency.

<project>
...
 <dependencies>
 <dependency>
 <groupId>org.neo4j</groupId>
 <artifactId>neo4j-kernel</artifactId>
 <version>1.9</version>
 <type>test-jar</type>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit-dep</artifactId>
 <version>4.11</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>org.hamcrest</groupId>
 <artifactId>hamcrest-all</artifactId>
 <version>1.3</version>
 <scope>test</scope>
 </dependency>
 ...
 </dependencies>
...
</project>

Observe that the <type>test-jar</type> is crucial. Without it you would get the common neo4j-kernel jar, not the one containing the testing facilities.

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

[Tip]Tip

For the full source code of this example see: Neo4jBasicDocTest.java

Before each test, create a fresh database:

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

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 TestGraphDatabaseFactory()
 .newImpermanentDatabaseBuilder()
 .setConfig( config )
 .newGraphDatabase();

Copyright © 2013 Neo Technology


Prev Up Next
Home

AltStyle によって変換されたページ (->オリジナル) /