dbUnit, useful more than just for unit tests

I really like dbUnit for unit tests, but I like it more for other
tasks, as exporting data from the database in xml or Excel formats with
a few lines of code and without bothering about writing xml tags or
interacting with POI to write Excel cells.

For
instance the next code can be used to export the result of a query into
an Excel file.

public class Report {

    private DataSource dataSource;

    public void exportData() throws Exception {

        IDatabaseConnection connection = new DatabaseConnection(dataSource
                .getConnection());

        try {

            // partial database export
            QueryDataSet partialDataSet = new QueryDataSet(connection);

            String query =
                    "SELECT a, b FROM t WHERE a = 'whatever'");

            partialDataSet.addTable("Report", query);
            XlsDataSet.write(partialDataSet, new FileOutputStream(
                    "report.xls"));

        } finally {
            connection.close();
        }

    }

2 thoughts on “dbUnit, useful more than just for unit tests

  1. There’s even a way to integrate Spring’s AbstractTransactionalSpringContextTests with DBUnit. That way, you can insert some test data, do some query testing, and on teardown, the transaction is never comitted. None of your test data remains in the database. Now, that’s cool stuff! 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s