Cédric Chantepie

Testing JDBC code without a database, step by step with Acolyte

Testing persistence code is not trivial. A test database needs scripts to set it up again for each run, and tests running in parallel can interfere with each other through shared data. Unit tests have an even harder time: each one has to be isolated, and none should depend on what ran before it.

Acolyte takes another approach. It is a JDBC driver where you decide what each connection answers. Your persistence code runs unchanged, but the statements it executes are matched against cases you declare, and each case returns the result you want. There is no data store to maintain, so each test is isolated by design.

To make this concrete, I prepared an interactive demo: acolyte-play-demo.onrender.com. A screencast walking through it is available at youtu.be/j05x1254_D0.

Setting up the connection

The demo follows the two steps Acolyte relies on:

  1. Route access cases: define which statements the connection handles. You can use one connection per case, or one connection for many cases.
  2. Declare the JDBC result for each case.

Once done, the connection can be passed anywhere your code expects a JDBC connection.

Empty setup page, with no route defined yet

The first route matches statements with a pattern. Here, the pattern ^SELECT id, level, label FROM form_tbl$ handles that exact query. The tour limits the parameter types to keep things simple, but Acolyte handles any JDBC type.

Defining the route pattern for a SELECT statement

For this route, the result is a result set with three columns (id, level, and label) and their types. You can also declare an error instead, to check how your code reacts to a failing statement.

Declaring the result set columns and types

Rows can be entered directly in the form, one per line, matching the declared columns.

Result set rows entered in the form

The route summary then shows the statement and its result: here, 9 rows of three columns.

Route summary showing the statement and its result set

Running the connection

Once the connection is defined, the run page lets you execute statements against it, as your code would. Here, the query is the one routed above.

Run page with the SELECT statement typed in

Why it fits unit tests

The demo shows the core idea: the persistence code only sees a JDBC connection, so you test what it does with the results, not how a database stores them. Each connection carries only the statements the test cares about, which keeps tests independent and makes it easy to simulate edge cases, such as an unexpected error.

Acolyte is open source. Documentation, sources and releases are on GitHub.