我不喜歡繼承dbunit的類,所以我們在JunitTest 的類里增加這個變量:
public class Test2 extends TestCase {
private IDatabaseTester databaseTester;
protected void setUp() throws Exception { }
protected void tearDown() throws Exception { }
}
public class Test2 extends TestCase {
private IDatabaseTester databaseTester;
protected void setUp() throws Exception {}
protected void tearDown() throws Exception {}
}
然后,我們可以該寫 setUp() 方法了,無非是連接數(shù)據(jù)庫,把數(shù)據(jù)倒入到表里。
protected void setUp() throws Exception {
databaseTester = new JdbcDatabaseTester("com.mysql.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/test", "root", "123");
IDataSet dataSet = getDataSet();
databaseTester.setDataSet( dataSet );
databaseTester.onSetup();
}
protected IDataSet getDataSet() throws Exception
{
return new FlatXmlDataSet(new FileInputStream(new File("dataset.xml")));
}
protected void setUp() throws Exception {
databaseTester = new JdbcDatabaseTester("com.mysql.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/test", "root", "123");
IDataSet dataSet = getDataSet();
databaseTester.setDataSet( dataSet );
databaseTester.onSetup();
}
protected IDataSet getDataSet() throws Exception
{
return new FlatXmlDataSet(new FileInputStream(new File("dataset.xml")));
}
然后是 tearDown 方法
protected void tearDown() throws Exception
{
databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
databaseTester.onTearDown();
}
protected void tearDown() throws Exception
{
databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
databaseTester.onTearDown();
}