DbUnit 是在JUnit的基礎上擴充而成的Java單元測試架構。
如果你的商務邏輯涉及到了對資料庫中記錄的增、刪、改、查操作,而你又不想每次都手動到資料庫裡查詢,來驗證你的商務邏輯,那麼DbUnit可以協助你。實際上,如果你的單元測試中只有少量商務邏輯對資料庫進行了操作,那麼,DbUnit在單元測試中的優勢還體現不出來,但是,如果你的單元測試用例中有大量的DAO操作,那麼全憑手動執行資料庫查詢,講造成工作效率降低,而且可能會遺漏功能點。而且,在迴歸測試中,驗證DAO操作的工作不能重用。
現在就讓我們開始認識DbUnit吧!首先介紹org.dbunit.DatabaseTestCase.java類,源碼如下:
package org.dbunit;
import junit.framework.TestCase;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.operation.DatabaseOperation;
/** *//**
* @author Manuel Laflamme
* @version $Revision: 1.11 $
* @since Feb 17, 2002
*/
public abstract class DatabaseTestCase extends TestCase
...{
public DatabaseTestCase()
...{
}
public DatabaseTestCase(String name)
...{
super(name);
}
/** *//**
* Returns the test database connection.
*/
protected abstract IDatabaseConnection getConnection() throws Exception;
/** *//**
* Returns the test dataset.
*/
protected abstract IDataSet getDataSet() throws Exception;
/** *//**
* Close the specified connection. Ovverride this method of you want to
* keep your connection alive between tests.
*/
protected void closeConnection(IDatabaseConnection connection) throws Exception
...{
connection.close();
}
/** *//**
* Returns the database operation executed in test setup.
*/
protected DatabaseOperation getSetUpOperation() throws Exception
...{
return DatabaseOperation.CLEAN_INSERT;
}
/** *//**
* Returns the database operation executed in test cleanup.
*/
protected DatabaseOperation getTearDownOperation() throws Exception
...{
return DatabaseOperation.NONE;
}
private void executeOperation(DatabaseOperation operation) throws Exception
...{
if (operation != DatabaseOperation.NONE)
...{
IDatabaseConnection connection = getConnection();
try
...{
operation.execute(connection, getDataSet());
}
finally
...{
closeConnection(connection);
}
}
}
////////////////////////////////////////////////////////////////////////////
// TestCase class
protected void setUp() throws Exception
...{
super.setUp();
executeOperation(getSetUpOperation());
}
protected void tearDown() throws Exception
...{
super.tearDown();
executeOperation(getTearDownOperation());
}
}