This working groovy example is designed to demonstrate how to use the dbunit ANT tasks.
To discover the true power of dbunit you need to read the doco and try out the examples:
http://www.dbunit.org/
Example
Run as follows and discovers an unmatching row of data in the database
$ groovy dbunit
[delete] Deleting directory /home/mark/Files/Dev/groovy/sql/build
[dbunit] Executing compare:
[dbunit] from file: /home/mark/Files/Dev/groovy/sql/dbunit.xml
[dbunit] with format: flat
Caught: : junit.framework.ComparisonFailure: value (table=TEST1, row=2, col=Y) expected:<300[1]> but was:<300[0]>
dbunit.xml
This file contains the expected database data:
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<TEST1 ID="1" X="10" Y="1000"/>
<TEST1 ID="2" X="11" Y="2000"/>
<TEST1 ID="3" X="12" Y="3001"/>
<TEST1 ID="4" X="13" Y="4000"/>
<TEST1 ID="5" X="14" Y="5000"/>
<TEST1 ID="6" X="15" Y="6000"/>
</dataset>
dbunit.groovy
The groovy script creates the H2 database and populates it with data. After which it runs dbunit to make sure the correct data was loaded:
//
// Dependencies
// ============
//
import groovy.sql.Sql
@Grapes([
@Grab(group='com.h2database', module='h2', version='1.3.167'),
@Grab(group='org.dbunit', module='dbunit', version='2.4.8'),
@Grab(group='org.slf4j', module='slf4j-simple', version='1.6.4'),
@GrabConfig(systemClassLoader=true),
])
//
// Main program
// ============
//
// Connection properties
def driver = "org.h2.Driver"
def url = "jdbc:h2:build/db/test"
def user = "user"
def pass = "pass"
// Cleanup
def ant = new AntBuilder()
ant.delete(dir:"build")
// Add the dbunit task into the ANT builder
ant.taskdef(name:"dbunit", classname:"org.dbunit.ant.DbUnitTask")
// Populate the test database
def sql = Sql.newInstance(url, user, pass, driver)
sql.execute("CREATE TABLE test1 (id identity, x varchar(10), y varchar(10))")
sql.execute("INSERT INTO test1 (x,y) VALUES (10,1000)")
sql.execute("INSERT INTO test1 (x,y) VALUES (11,2000)")
sql.execute("INSERT INTO test1 (x,y) VALUES (12,3000)")
sql.execute("INSERT INTO test1 (x,y) VALUES (13,4000)")
sql.execute("INSERT INTO test1 (x,y) VALUES (14,5000)")
sql.execute("INSERT INTO test1 (x,y) VALUES (15,6000)")
sql.close()
// Compare the data
ant.dbunit(driver:driver, url:url, userid:user, password:pass) {
compare(src:"dbunit.xml", format:"flat")
dbconfig {
property(name:"datatypeFactory", value:"org.dbunit.ext.h2.H2DataTypeFactory")
}
}