Java Reference
In-Depth Information
assertEquals(id, user.getId());
IDataSet expectedDataSet = getDataSet("/user.xml");
IDataSet actualDataSet = dbunitConnection.createDataSet();
Assertion.assertEquals( expectedDataSet, actualDataSet );
}
}
We start by extending the DbUnit class AbstractDbUnitTestCase B . The @Test
method testAddUser() first creates and populates a User object C .
Next, we ask DAO to persist the User object and check that it generates a valid
ID D (a positive value, in this case) and that the returned ID matches the object.
Such checking is important in situations where the caller needs to use the new ID
(for instance, in a web page that generates a link to edit the newly created object).
It may sound trivial and redundant in this case, but you'd be surprised by how
often the ID isn't set correctly in more complex combinations (like multilayered
applications with Spring managing transactions and Hibernate being used as the
persistence layer).
At E we use the same dataset (user.xml) and same method ( getDataSet() ) as the
previous example—it's always a good practice to reuse code and testing artifacts. At F
IDatabaseConnection.createDataSet() returns a dataset containing all tables (with
all rows) in the database. Finally, at G Assertion.assertEquals() compares both
datasets, and if a discrepancy is found, it fails with the proper message. Notice that we
did not statically import this method. Because both JU nit's Assert and DbUnit's
Assertion have assertEquals() methods, if you static import both, chances are a call
to assertEquals() will reference the wrong one.
E
F
G
Best practice: use a helper class to create and assert object instances
In the previous example, testGetUserById() fetched an object from the database
and asserted its attributes, but testAddUser() did the opposite (instantiated a
new object, filled its attributes, and then inserted it in the database). As your test
cases grow, more and more tests will need to do the same. To avoid the DRY (don't
repeat yourself) syndrome, it's better to create a helper class containing methods
and constants for these tasks. Doing so improves reuse in the Java classes and
facilitates maintenance of dataset files. If you use Java 5 and static imports,
accessing members in this helper class is simple. Listing 17.8 shows a revised ver-
sion of testAddUser() using this practice.
Listing 17.8
Revised version of testAddUser() , using a helper class
[...]
import static EntitiesHelper.*;
[...]
public class UserDaoJdbcImplTest extends AbstractDbUnitTestCase {
[...]
B
 
 
 
 
 
 
 
Search WWH ::




Custom Search