初次使用ant+DbUnit,用ant可以实现,也可以直接写DbUnit的测试代码可现。
dataset.xml
代码:
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<EMPLOYEE id='1'
firstname='Sager'
lastname='Xiao' />
<EMPLOYEE id='2'
firstname='Cheung'
lastname='Zhang' />
<EMPLOYEE id='3'
firstname='Sword'
lastname='Lu' />
</dataset>
build.xml
代码:
<project name="MyDbUnit" basedir="." default="db-load">
<property name="lib.dir" value="D:\Java\lib"/>
<property name="dbunit.jar" value="${lib.dir}\dbunit-2.1\dbunit-2.1.jar"/>
<property name="junit.jar" value="${lib.dir}\junit3.8.1\junit.jar"/>
<property name="junitdoclet.jar" value="${lib.dir}\JUnitDoclet.1.0.2\JUnitDoclet.jar"/>
<property name="jdbc.jar" value="${lib.dir}\mysql-connector-java-3.0.11-stable-bin.jar"/>
<property name="classes.dir" value="./bin"/>
<path id="test.classpath">
<pathelement location="${dbunit.jar}"/>
<pathelement location="${junit.jar}"/>
<pathelement location="${junitdoclet.jar}"/>
<pathelement location="${jdbc.jar}"/>
</path>
<target name="prepare">
<taskdef name="dbunit" classname="org.dbunit.ant.DbUnitTask"
classpathref="test.classpath"/>
</target>
<target name="db-load" depends="prepare">
<dbunit driver="com.mysql.jdbc.Driver"
supportBatchStatement="false"
url="jdbc:mysql://localhost/test"
userid="root"
password="sql">
<operation type="CLEAN_INSERT" src="dataset.xml" />
</dbunit>
</target>
</project>
直接的测试代码,运行JUnit测试就可以将数据导入数据库:
代码:
/*
* Created on 2004-10-12
*/
package com.sager.dbunit;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import org.dbunit.DatabaseTestCase;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
/**
* @author Sager
*
*/
public class SampleTest extends DatabaseTestCase {
public SampleTest(String name) {
super(name);
}
/**
* @see org.dbunit.DatabaseTestCase#getConnection()
*/
protected IDatabaseConnection getConnection() throws Exception {
Class driverClass = Class.forName("com.mysql.jdbc.Driver");
Connection jdbcConnection = DriverManager.getConnection(
"jdbc:mysql://localhost/test", "root", "sql");
return new DatabaseConnection(jdbcConnection);
}
/**
* @see org.dbunit.DatabaseTestCase#getDataSet()
*/
protected IDataSet getDataSet() throws Exception {
return new FlatXmlDataSet(new FileInputStream("dataset.xml"));
}
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.REFRESH;
}
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.NONE;
}
public void testMe() {
System.out.println("Testing...");
}
}
本文地址:http://com.8s8s.com/it/it30899.htm