Java Reference
In-Depth Information
which are not checked until commit time, are satisfied. The downside of this
approach is that it changes the database, which requires each test to initialize the
database to a known state.
We could also enhance the tests to verify that an object's fields are mapped cor-
rectly by validating the contents of the database tables. After inserting the object
graph into the database, the test verifies that the database contains the expected
rows and column values. A test can verify the contents of the database by using to
JDBC to retrieve the data. Alternatively, it could use DbUnit [DbUnit], which is a
JU nit extension, to compare the database tables against an XML file that contains
the expected values. However, although this approach is more thorough it is
extremely tedious to develop and maintain these kinds of tests. In addition, the
tests don't detect a missing mapping for a newly added field or property. Conse-
quently, a much better way to test that classes and field/properties are mapped
correctly is, as I describe later, to test the ORM document directly.
Tests that insert, update, and delete persistent objects are extremely useful, but
they can be challenging to write. One reason is because some objects have lots of
states that need to be tested. Another reason for the complexity is the amount of
setup often required. Tests may have to create other persistent objects that are ref-
erenced by the object being tested. For example, in order to persist a Pendin-
gOrder and its line items, the test has to initialize the database with Restaurant
and MenuItems . In addition, an object's public interface doesn't usually allow its
fields to be set directly and so a test must call a sequence of business methods with
the correct arguments, which can involve even more setup code. As a result, it can
be challenging to write good persistence tests.
The other drawback with this approach is that executing the tests can be slow
because of the number of times the database is accessed. Each persistent class can
have multiple tests that each consists of multiple steps. Each step makes multiple
calls to the ORM framework, which executes multiple SQL statements. Conse-
quently, these tests usually take too long to be part of the unit tests suite and
instead should be part of the functional tests.
Even though these persistent object tests can be difficult to write and can take
a significant amount of time to execute, they are an important part of the test suite
for a domain model. If necessary you can always start off by writing tests that just
save objects in the database and over time add tests that update and delete objects.
Testing queries
We need to write database-level tests for some of the queries that are used by the
repositories. One basic way to test the queries is to execute each query once and
 
 
Search WWH ::




Custom Search