The rise of extreme programming methods has brought test-driven development and continuous integration into mainstream Java development practice. Using these technologies in Java server-side development can quickly become a nightmare if the right tools are not used. In this article, software developer Philippe Girolami describes how to handle continuous integration and how to use DbUnit and JUnit together to control the test environment End-to-end by setting the state of the database before each test.
One of the most important practices in software development is testing. By recommending Test-first development and continuous integration, extreme programming (Extreme PROGRAMMING,XP) pushes this logic to the limit, where testing is done as frequently as possible. Most non-XP development, however, has some form of testing, perhaps called regression testing, black-box testing, functional testing, or other names. Many projects use relational databases to store data, so all test strategies need to consider what happens in the database during each test: if the test keeps the test database in an inconsistent state, then all subsequent tests may fail! One way to avoid this is to set the database state to a known related state before each test. In this article, I'll explain how our team combines JUnit with DbUnit to do this, and how to automate the generation of test reports with Anthill. Although the setting may seem like a lot of work, it's not actually the case, and it has proven itself to be a useful tool.
Represents the contents of a database
DbUnit extends JUnit, which allows the database to be in a known state between Tests, helping to avoid problems that cause subsequent tests to fail or give incorrect results, which can occur if the test destroys the database. It can read the contents of the table and use Flatxmldataset to store it as XML, as shown in Listing 1:
Listing 1. Flatxmldataset sample
<dataset>
<OPERATOR
ID='APC (Washington/Baltimore)'
CODE='ABC5APC'
ENCODED_STRING='aabbcc'/>
<OPERATOR
ID='ASA Ritabell'
CODE='ABC6ASA R'
ENCODED_STRING='bbccdd'/>
<OPERATOR
ID='Advanced Info. Service PLC'
CODE='ABC1Adva'
ENCODED_STRING='ccddee'/>
<OPE_OPERATOR
ID='Aerial Communications Inc.'
CODE='ABC2Aeri'
ENCODED_STRING='ddeeff'/>
</dataset>
This dataset represents three columns in a database table named Ope_operator, as described in the last three rows in table 1:
Table 1. Table definition of data in Listing 1
Ope_operator |
Id |
Int |
CODE |
VARCHAR |
Encoded_string |
VARCHAR |
Each XML entity identifies a table in the database, and each attribute represents a column's value.