Java Reference
In-Depth Information
mapped statement that executes against the database. A test for a
SELECT
statement
populates the database with test data, executes the query, and verifies that it returns
the expected result. Similarly, a test for an
UPDATE
statement populates the database,
executes the update, and verifies the contents of the database. A good tool for writ-
ing these kinds of tests is DbUnit [DbUnit], which is an extension to
JU
nit that pro-
vides methods for initializing the database and verifying its contents. For example,
here is the outline of a test that for the
findPendingOrder
mapped statement. The
test uses the DbUnit method
DatabaseOperation.CLEAN_INSERT.execute()
to ini-
tialize the database with the data from the
XML
file pending-order-1.xml and exe-
cutes the query using a
SqlMapClientTemplate
:
public class DBUnitIBatisExampleTests extends TestCase {
private DatabaseConnection dbUnitConnection;
private SqlMapClientTemplate sqlMapClientTemplate;
public void setUp() throws Exception { … };
public void test() throws Exception {
FlatXmlDataSet dataSet = new FlatXmlDataSet(
getClass().getResourceAsStream(
"pending-order-1.xml"));
DatabaseOperation.CLEAN_INSERT.execute(
dbUnitConnection, dataSet);
PendingOrderDTO pendingOrder =
(PendingOrderDTO) sqlMapClientTemplate
.queryForObject("findPendingOrder", "1");
assertNotNull(pendingOrder);
…
}
…
}
For more information on how to write these kinds of tests, see the DbUnit docu-
mentation and the excellent book
JUnit Recipes
[Rainsberger 2004].
The downside of this approach is that the tests are time consuming to write
and execute. Mapped statements often require multiple tests to verify different
scenarios. One simplification, which is often a good way to start, is to write tests
that execute each
SQL
statement once without verifying either the return value or
the database. This is relatively easy to do and catches many common errors. In
addition, the tests will execute fairly quickly.
Search WWH ::
Custom Search