Java Reference
In-Depth Information
Best practice: define a superclass for your database tests
The UserDaoJdbcImplTest class in listing 17.6 defines four methods, but only one
is effectively a test case—the other three are helpers used in the testing infrastruc-
ture. As you add more test cases, the proportion tends to revert, although it's com-
mon to add more helper methods as well. These helpers can typically be reused by
other test classes.
Consequently, it's good practice to create a superclass that defines only these
infrastructure methods and then make the real test classes extend this super-
class. This best practice applies not only to DbUnit-based tests but also to test-
ing in general.
The class in the listing 17.6 example could be refactored into two classes, an
AbstractDbUnitTestCase superclass (with methods setupDatabase() , close-
Database() , and getDataSet() ) and the UserDaoJdbcImplTest properly speak-
ing (which for now contains only testGetUserById() ). The next example will use
this technique.
Now let's look at DatabaseOperation in detail.
17.3.1
DatabaseOperation dissected
DatabaseOperation is the class used to send datasets to the database. Although
DbUnit makes good use of interfaces and implementations, DatabaseOperation is
one of the few concepts that isn't defined by an interface. Instead, it's defined as an
abstract class with an abstract method ( execute() , which takes as parameters a dataset
and a database connection). The reason for such different design is to facilitate its
use, because the abstract class also defines constants for its implementations (DbUnit
was created on Java 1.3/1.4 when there was no native enum), so the operations can be
executed with just one line of code, as we saw in the first example.
The implementations provided by DatabaseOperation as static fields are as follows:
UPDATE —Update the database with the dataset content. It assumes the rows in
the dataset already exist in the database (that is, the database contains rows with
the same primary keys as the rows in the dataset); if they don't exist, DbUnit will
throw an exception.
INSERT —Insert the dataset rows in the database. Similarly to UPDATE , DbUnit
will throw an exception if any row already exists. Because rows are inserted in
the order in which they appear in the dataset, care must be taken when
tables have foreign keys: rows must be defined in the dataset using the right
insertion order.
REFRESH —This is a mix of INSERT and UPDATE : rows that exist in the dataset but
not in the database are inserted, but rows that exist in both are updated.
DELETE —Delete from the database only the rows present in the dataset, in the
reverse order in which they appear in the dataset.
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search