Java Reference
In-Depth Information
known state before the test is run. This is achieved by using the same dataset and a
DELETE_ALL operation:
IDataSet setupDataSet = getDataSet("/user.xml");
DatabaseOperation.DELETE_ALL.execute(dbunitConnection, setupDataSet);
If we add this code and run the whole test again, the test fails:
junit.framework.AssertionFailedError: value (table=users, row=0, col=id):
expected:<1> but was:<2>
at junit.framework.Assert.fail(Assert.java:47)
at org.dbunit.Assertion.assertEquals(Assertion.java:147)
at org.dbunit.Assertion.assertEquals(Assertion.java:80)
Now the number of rows is correct (because we deleted all rows from the users table
before running the test), but the ID of the inserted row doesn't match what we expect.
This is another common problem, and it happens frequently when the database gen-
erates the ID . Although we cleaned up the rows, we didn't reset the primary key gener-
ation, so the next row inserted has an ID of 2 and not 1 as we expected.
There are many solutions for this issue, ranging from simple (like ignoring the
ID column in the comparison) to sophisticated (like taking control of how ID s are
generated—we show this approach in the next chapter). For now, let's just ignore
the ID column, using the method Assertion.assertEqualsIgnoreCols() instead of
Assertion.assertEquals() :
Assertion.assertEqualsIgnoreCols( expectedDataSet, actualDataSet, "users",
new String[] { "id" } );
Listing 17.9 shows the full method for our new test case.
Listing 17.9
Second approach for testAddUser()
[...]
public class UserDaoJdbcImplTest extends AbstractDbUnitTestCase {
@Test
public void testAddUserIgnoringIds() throws Exception {
IDataSet setupDataSet = getDataSet("/user.xml");
DatabaseOperation.DELETE_ALL.execute(dbunitConnection, setupDataSet);
User user = newUser();
long id = dao.addUser(user);
assertTrue(id>0);
IDataSet expectedDataSet = getDataSet("/user.xml");
IDataSet actualDataSet = dbunitConnection.createDataSet();
Assertion.assertEqualsIgnoreCols( expectedDataSet, actualDataSet,
"users", new String[] { "id" } );
}
}
Although ignoring the column is the simplest approach to the problem (in the sense
that it doesn't require any advanced technique), it introduces a maintenance bug:
now it's necessary to keep both the dataset file (user.xml) and the Java class (which
 
 
 
 
 
Search WWH ::




Custom Search