Java Reference
In-Depth Information
for test cases to roll back the transaction on teardown, and many frameworks (such as
Spring TestContext) follow this approach.
So what is the better approach, to commit or not? Again, there's no secret ingredi-
ent, and each approach has its advantages. We, in particular, prefer the commit
option, because of the following aspects:
If you're using an embedded database, speed isn't an issue. You could even re-
create the whole database before each test case.
As we mention in section 18.8.5, test cases can do cleanup on teardown when
necessary. And again, when using an embedded database, the cleanup is a
cheap operation.
If you roll back the transaction, the JPA vendor might not send the real SQL
to the database (for instance, Hibernate issues the SQL only at commit or if
session.flush() is explicitly called). There might be cases where your test
case passes, but when the code is executed in real life, if fails.
In some situations, you want to explicitly test how the persistent objects will
behave once outside a JPA transaction/session.
For these reasons, the test cases in this chapter manually handle the transac-
tion's lifecycle.
Now, without further ado, let's start testing it.
18.3
Preparing the infrastructure
Okay, we lied: before our first test, we need some more ado! More specifically, we
need to define the infrastructure classes that our real test case classes will extend
(remember section 17.3's best practice: define a superclass for your database tests).
Figure 18.1 shows the class diagram for such infrastructure.
Figure 18.1
Class diagram of the testing infrastructure
 
 
 
 
Search WWH ::




Custom Search