16 Ağustos 2010 Pazartesi

Use DbUnit With Maven

dbunit is a useful tool for populating test data into databases on the fly.
It is also useful to use this tool to populate application configuration information.
This article demonstrates how to use dbunit with maven.

We require jdbc drivers for our database. Assuming we are using oracle, dbunit plugin's dependency configuration will be as follows:

<dependency>
   <groupId>com.oracle</groupId>
   <artifactId>ojdbc14</artifactId>
   <version>10.2.0.2.0</version> 
</dependency>
                  
We also need connection information for our database. We'll use following connection information in our dbunit configuration:

host: jdbc:oracle:thin:@localhost:1521:XE
username: hr
password: hr
driver: oracle.jdbc.driver.OracleDriver

Putting it all together, following is an example configuration for dbunit:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>dbunit-maven-plugin</artifactId>
    <version>1.0-beta-3</version>
    <configuration>
        <dataTypeFactoryName>org.dbunit.ext.oracle.OracleDataTypeFactory</dataTypeFactoryName>
        <driver>oracle.jdbc.driver.OracleDriver</driver>
        <username>hr</username>
        <password>hr</password>
        <url>jdbc:oracle:thin:@localhost:1521:XE</url>
        <src>src/test/resources/sample-data.xml</src>
        <type>CLEAN_INSERT</type>
        <schema>HR</schema>
        <skip>${skipTests}</skip>
        <transaction>true</transaction>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.2.0</version>
        </dependency>
    </dependencies>
</plugin>


Based on this configuration, our dataset file resides in src/test/resources/sample-data.xml file. This file contains our test data. Execute following command to persist the data inside sample-data.xml into the database.

> mvn dbunit:operation

Yet, we don't know how to prepare and/or what to put inside sample-data.xml. If you have a ready to use database, you may not need to prepare sample-data.xml file from scratch. There is another command to export database tables into a dataset file.

> mvn dbunit:export

Upon invoking this command, a new file will be generated under target/dbunit/export.xml which will contain all your test data. You can, later, use this file to reinitialize your test database using "mvn dbunit:operation" command.

Additional Resources:

Maven DBUnit Plugin Homepage:
http://mojo.codehaus.org/dbunit-maven-plugin

DBUnit Getting Started Guide:
http://www.dbunit.org/howto.html


DBUnit Best Practices:
http://www.dbunit.org/bestpractices.html