Java Reference
In-Depth Information
A FilteredDataSet decorates a given dataset using an ITableFilter , which in turn is
a DbUnit interface that defines which tables belongs to a dataset and in what order
they should be retrieved. In the previous example, the constructor implicitly creates a
SequenceTableFilter , which returns the tables in the order defined by the array
passed as a parameter.
Finally, a third option is to use a QueryDataSet , where you explicitly indicate which
table should be present in the dataset. The next example returns a dataset that has the
exact same contents as the previous example:
QueryDataSet actualDataSet = new QueryDataSet(dbunitConnection);
actualDataSet.addTable("users");
Comparing the three options, the overloaded createDataSet() is obviously simpler
in this case. But the other options have their usefulness in different scenarios:
QueryDataSet is more flexible, because you can also provide the query that will
be used to populate the dataset (if you don't provide one, it assumes SELECT *
FROM table_name ). Using a query, you can narrow the field even more, by select-
ing only the rows the test case is interested in, which is useful when the database
contains a lot of data, for example:
QueryDataSet actualDataSet = new QueryDataSet(dbunitConnection);
actualDataSet.addTable("users",
"select * from users where id = " + id);
FilteredDataSet can be used with any ITableFilter , such as a filter that
returns tables in the right foreign-key dependency order (as will be shown in
section 17.6).
17.4.2
Ignoring columns
If you run the previous test method alone, it will pass. But if you append it to the exist-
ing UserDaoJdbcImplTest class and run the whole class, it will fail:
junit.framework.AssertionFailedError: row count (table=users) expected:<1>
but was:<2>
at junit.framework.Assert.fail(Assert.java:47)
This is a common problem when using DbUnit—and one of the most annoying. A
test case passes when it's run alone but fails when run as part of a suite. In this par-
ticular case, our user.xml dataset has only one row, and this is what we assume the
database should contain after we insert the User object. When many tests are run, it
fails because the database contains something else. Where does the extra row come
from? From the previous test ( testGetUserById() ) execution, because that method
also inserted a row. We could say the culprit is the previous test, which did not
clean itself up. 7 It's the test case's responsibility to make sure the database is in a
7
The DbUnit documentation states: “Good setup don't need cleanup” and you “should not be afraid to leave
your trace after a test.” This isn't always true, though, as you'll see in section 17.8.
 
 
 
 
 
 
 
Search WWH ::




Custom Search