Java Reference
In-Depth Information
The best “practice” here is to be aware of this problem and plan in advance. With
this in mind, the following techniques can mitigate the problem:
Use the same dataset for loading/storing an object.
Keep datasets small, restricting the tables and columns compared.
If you always use the same values for the same objects (as described in “Best
practice: use a helper class to create and assert object instances”), at least you
can apply the changes with just one search-and-replace command. Or, in a
more sophisticated approach, you could keep smaller XML files for groups of
objects and then use XML include or CompositeDataSet to join them. Keep in
mind, though, that any of these approaches brings more complexity to the test
cases, and you might end up with something that's harder to maintain than a
good, old search and replace.
17.8.6
Test cleanup
In all examples so far, the test cases set up the database but didn't bother to clean it up
after they did their job. This is typically a good practice and is indeed one of the best
practices endorsed by DbUnit.
Notice our emphasis on the typically , though. The problem of not cleaning up the
database after the test is done is that a test case could make another test's life misera-
ble if it inserts data that's hard to be cleaned, like rows with foreign keys. Back to the
users/telephones tables example, let's say a test case adds one row to each table, with
the telephones row having a foreign key to users, and this test case doesn't clean up
these rows after it's run. Then a second test case is going to use the same users row,
but it doesn't care about the telephones table. If this test tries to remove the users row
at setup, it will fail because of a foreign key violation.
So, long story short, although typically a good setup doesn't need cleanup, it
doesn't hurt to clean up, especially when the test case inserts rows with foreign
key constraints.
17.9
Summary
The persistence layer is undoubtedly one of the most important parts of any enter-
prise application, although testing it can be a challenge: test cases must be agile, but
database characteristics make them bureaucratic. Although JU nit itself doesn't have
an answer to this problem, many tools do. In this chapter, we used DbUnit to validate
an application's database access.
DbUnit is a stable and mature project, comprising a few dozen interfaces, imple-
mentations, and helpers. Despite this high number of classes, DbUnit usage is rela-
tively simple, because it consists of setting up the database before a test is run and
comparing its state afterwards.
Although DbUnit is a great tool, it's a low-level library, which provides the basic
blocks for database testing. To use it efficiently, it's necessary to define infrastructure
classes and methods that at the same time leverage DbUnit strengths and provide
 
 
 
 
 
Search WWH ::




Custom Search