Different modes for H2 Database Engine for testing

When testing software that requires a database for persisting data there are different ways to do this. One way is to use a real database engine instance for testing purpose only. Setting up a full scale database server is totally oversized for testing purpose. So using a dedicated simply to use database is a good way. Furthermore the data may not persisted as after the test the data is not necessary anymore. For performance reasons a non-persistent database engine would be great. There are many solutions for in-memory database testing. One of them is H2. Let’s have a look how H2 can be configured for this purpose.

Using H2 database

The H2 database is available via maven central.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.190</version>
</dependency>

Setting up H2

In order to use H2 a connection can be allocated by the java default mechanism that supports loading a jdbc connection. Allocating a database connection is possible via:

DriverManager.getConnection("connectionUrl");

When using another database engine, the setup is exactly the same. There is simply one difference: There is another connection url and maybe some connection parameters that influence the setup.

H2 connection Urls

The following table shows different connection urls for the H2 database. Each of them may be apropriate, depending on the test setup.

Url Description
jdbc:h2:mem:test multiple connections to one database called test possible
jdbc:h2:mem: creates a private database for each connection
jdbc:h2:test storing the data in the subfolder test

Alternatives

The H2 database engine is not the only lightweight database engine. There is e.g. hsql or Apache Derby. Both databases are also easy to use and have the same focus and are perfectly to use for unit and integration testing. All of them support in-memory database engines that forget the information after test.

Sources

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.