Java Reference
In-Depth Information
Don't make the mistake of assuming databases can be substituted at will; there are
always incompatibilities, even if you use an ORM tool. The sooner you catch these
issues, the better.
17.8.3
Create complementary tests for loading and storing data
As the old sayings goes, “everything that goes up must come down.” If you write a test
case that verifies an object is correctly stored in the database, chances are you should
write the test that asserts it's loaded correctly. And if you keep that in mind when you
write one of them, it makes it easy to write the other one; you could reuse the same
dataset or even write special infrastructure to handle both.
17.8.4
When writing load test cases, cover all the basic scenarios
All versions of testGetUserById() used in this chapter covered just one scenario: the
database contained a row with the tested ID and only that row. That was enough for
the purpose of describing the techniques, but in a real project you should test other
scenarios, such as testing an ID that doesn't exist in the database, testing an empty
database, testing when more than one row is available, and testing joins when multiple
rows are available.
The last scenario deserves special attention, because it's a common issue when you
use an ORM tool and you're testing a method that uses a complex query where one or
more tables are selected using a join. Let's say a User object has a List<Telephone>
relationship, the Telephone class is mapped to a telephones table with a foreign key to
the users table, you're using JPA in the persistence layer, and the getUserById() must
do a join fetch to get all telephones in just one query (if you aren't familiar with these
concepts, don't worry; we explain them better in chapter 18). You write just one test
case, where the dataset contains only one row in both users and telephone rows, and
you implement the JPA query as something like "from User user left join fetch
user.telephones where user.id = ?" . Your test case passes, so you commit your code.
Then once the application is in production, and a user happens to have more than
one telephone, your code returns two users for the query. After half a day of debug-
ging, you figure out the fix would be to change the query to "select distinct(user)
from User user left join fetch user.telephones where user.id = ?" . Had your ini-
tial test case covered more than the canonical scenario, you wouldn't have had this
bug. This particular issue is common.
17.8.5
Plan your dataset usage
As your application grows and you write more database test cases, your datasets
become hard to manage. If you have 20 dataset XML files containing a particular
table, and that table changes, then you have to change 20 XML files. This is prob-
ably the biggest DbUnit drawback, and unfortunately it's a problem without a
clear solution.
 
 
 
 
 
 
Search WWH ::




Custom Search