Java Reference
In-Depth Information
Persistence testing
Real challenges start when you have to include other systems in your testing process.
Troubles might be caused even by the necessity of testing interactions with a relational
database. In
Chapter 5
,
Combining Persistence with CDI
, we introduced the JPA. Now it's
time to describe how you can test your interactions with it.
There are a few issues that have to be considered when testing database-related code:
• How to verify that data was really inserted to the database?
• How to maintain the database state between tests and how to automatically clean
it?
Arquillian persistence extension allows you to test both these things. Before running a test,
you can seed your database from
.xml
,
.xls
,
.yaml
,
.json
, or custom SQL scripts.
It's done by just annotating the test case using the
@UsingDataSet("path-to-
seeding-file")
annotation. After the test execution, you can compare the database
state against another file, this time using the
@ShouldMatchDataSet("path-to-
dataset")
annotation. Let's look at an example:
@Test
@UsingDataSet("datasets/seats.yml")
@ShouldMatchDataSet("datasets/expected-seats.yml")
public void shouldMakeACleanup() throws Exception {
// given
// from annotation
// when
ticketService.doCleanUp();
// then
// from annotation
}
The
seats.yml
and
expected-seats.xml
files are just simple YAMLs placed in
/src/test/resources/datasets
. The first file contains
SeatType
:
Seat_Type:
- description: test