Skip to main content
Version: 4.0.x

Testing

DB plugin includes a JUnit 5 test harness backed by an embedded H2 database, so you can test database-backed code without connecting to a real back end.

Installation​

The harness lives in its own module, separate from the db-test contract suite used to test DB plugin itself. Add it as a test dependency:

<dependency>
<groupId>com.brightspot.db</groupId>
<artifactId>test-db</artifactId>
<version>4.0.1</version>
</dependency>

If you need the H2-backed Database implementation directly—for example, to configure a custom Supplier—also add:

<dependency>
<groupId>com.brightspot.db</groupId>
<artifactId>h2</artifactId>
<version>4.0.1</version>
</dependency>

Writing a test against an H2-backed database​

Extend AbstractDatabaseTest to run a test class against an in-memory H2 database. The base class wires up TestDatabaseExtension, which installs the database as the default before all tests in the class and clears the override afterward:

1
class ArticleTest extends AbstractDatabaseTest {
2
3
@Test
4
void saveAndLoad() {
5
Article article = new Article();
6
7
article.setTitle("Hello world");
8
article.save();
9
10
assertThat(Query.from(Article.class).first().getTitle()).isEqualTo("Hello world");
11
}
12
}

For Recordable types, AbstractRecordTest extends AbstractBeanTest with the same database setup, plus standard checks that the type does not override equals or hashCode.

Supplying a different database​

By default, TestDatabaseExtension installs the database from DefaultTestDatabaseSupplier, an in-memory H2 instance. Annotate a test method with @TestDatabase to supply a different Database instead:

1
@TestDatabase(CustomDatabaseSupplier.class)
2
@Test
3
void queryWithCustomDatabase() {
4
// ...
5
}

The annotation's value must be a Supplier<Database> with a public no-argument constructor.

note

Starting with DB plugin 3.4.0, com.psddev:dari-h2 and com.psddev:test-db are published as com.brightspot.db:h2 and com.brightspot.db:test-db. Package names are unchanged (com.psddev.dari.h2, com.psddev.test.db). Update any direct dependency on the old coordinates to the new ones when you adopt this version—the old coordinates resolve to the new modules only once your build is on a dependency BOM that declares the relocation.