Java Reference
In-Depth Information
Best practice: don't hardcode values
This example uses hard coded 1s in method calls:
IDataSet setupDataset =
getReplacedDataSet("/user-token.xml", 1);
DatabaseOperation.INSERT.execute(dbunitConnection,
setupDataset);
User user = dao.getUserById(1);
If you didn't write that code (or even if you wrote it a long time ago), the following
questions might pop up in your mind: What does the 1 in the first line stands for?
Is that method replacing just one line? Does it sound like that 1 is directly related
to the 1 in the third line? Now take a look back at the testGetUserById() method
from the previous listing. Would you have the same doubts? This example illus-
trates how a subtle change (which costs just a few seconds of a developer's time)
makes code much more understandable (and consequently easier to maintain).
Create variables or constants whenever appropriate, even if the variable will be
used only once.
17.5.2
Handling NULL values
Another situation where a ReplacementDataSet is useful is to represent NULL values
( SQL 's NULL , not Java's null ) in a dataset. The way DbUnit handles NULL in FlatXml-
DataSet files is tricky and deserves clarification:
If a column exists in the database but is missing in an XML line, then the value
of that column (for that row in the dataset) is assumed to be NULL .
1
But that applies only if the column was present in the first line of XML . DbUnit
uses the first line to define which columns a table is made of.
2
This is true unless the database columns are defined in a DTD !
3
It's frustrating to spend hours trying to figure out why your test case is failing, just to
realize you were caught by a DbUnit idiosyncrasy. 8 Let's try to make it clearer with a
naive example, where we have two XML files with the exact same lines but in different
order (as shown by listings 17.12 and 17.13).
Listing 17.12
user-ok.xml, where the first line has all columns
<?xml version="1.0"?>
<dataset>
<users id="1" username="ElDuderino"
first_name="Jeffrey" last_name="Lebowsky" />
<users id="2" username="TheStranger"/>
</dataset>
8
This situation has improved in more recent versions of DbUnit. Although the idiosyncrasy still exists, at least
now DbUnit is aware of the problems it can cause and logs a warning message whenever it finds a line in the
XML file with different columns than the first one.
 
 
 
 
 
Search WWH ::




Custom Search