Java Reference
In-Depth Information
■
DELETE_ALL
—Delete from the database all rows from each table present in the
dataset. Although it's an aggressive approach in many cases (such as when
the database is shared by many developers or it contains data that shouldn't
be deleted), it's the simplest way to guarantee the state of the database
(because sometimes the database might contain data that isn't deleted by
DELETE
and hence can interfere in the test results).
■
TRUNCATE
—Same purpose as
DELETE_ALL
, but faster, because it uses the
SQL
's
TRUNCATE
TABLE
. The only drawback is that not all databases support such
SQL
operation.
■
CLEAN_INSERT
—Composite operation, first calls
DELETE_ALL
, then
INSERT
, using
the same dataset.
■
TRANSACTION(operation)
—Not exactly a field but a method. It creates a
Data-
baseOperation
that will wrap another operation inside a database transaction.
It's particularly useful in cases where tables have circular dependency and rows
can't be inserted outside a transaction with deferred constraints.
■
CLOSE_CONNECTION(operation)
—Another wrapper, it executes the operation
and then automatically closes the connection. This can be useful in tear-
down methods.
■
NONE
—An empty operation that does nothing.
That's it; we wrote our first DbUnit test case and set the foundation for most of the
tests to come.
17.4
Asserting database state with datasets
Another common use of datasets is to assert that the database has the right data after
an insert or update. Back to our
DAO
example: we need a test case for the
addUser()
method, and the workflow for this test is the opposite from
getUserById()
's test.
Here we first create a
User
object, ask our
DAO
to persist it, then use a DbUnit dataset
to assert that the data was properly inserted. The code snippet in listing 17.7 is our
first attempt at such a test case.
Listing 17.7
Test case for
addUser()
method
[...]
import
org.dbunit.Assertion;
[...]
public class
UserDaoJdbcImplTest
extends
AbstractDbUnitTestCase {
[...]
@Test
public void
testAddUser()
throws
Exception {
User user =
new
User();
user.setFirstName("Jeffrey");
user.setLastName("Lebowsky");
user.setUsername("ElDuderino");
long
id = dao.addUser(user);
assertTrue(id>0);
B
C
D