测试
DatabaseTestCase类
DBUnit提供了一个抽象类: DatabaseTestCase,它继承自 JUnit的 TestCase,这个类有两个方法需要重载:
protecte abstract IDatabaseConnection getConnection() throws Exception;
protected abstract IDataSet getDataSet() throws Exception;
getConnection用于告诉测试用例如何找到数据库连接;getDataSet用于告诉测试用例如何获取测试数据文件(dataSet.xml)。下面我们先继承这个抽象类编写测试用例:
package com.wang.dbunit;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import com.wang.dbunit.Account;
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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;
public class HelloDBUnit extends DatabaseTestCase
{
static Logger logger
= LogManager.getLogger(HelloDBUnit.class.getName());
privatestatic ApplicationContext context;
protected Properties props = new Properties();
public HelloDBUnit() throws IOException
{
super();
props.load(Resources.getResourceAsStream(
"database.properties"));
context = newClassPathXmlApplicationContext(
"classpath:ApplicationContext.xml");
}
////////////////////////////////////////////////
@Override
protected IDatabaseConnection getConnection() throws Exception
{
DataSourcedataSource
= (DataSource)context.getBean("dataSource");
Connectionconnection = dataSource.getConnection();
// 如果所用测试帐户是 DBA,为了避免出现 AmbiguousTableNameException
// 异常,下面必须改写为 newDatabaseConnection(connection, SCHEMA)
// 形式。注意SCHEMA 要大写**
return new DatabaseConnection(connection);
}
@Override
protected IDataSet getDataSet()throws Exception
{
return new FlatXmlDataSet(
new FileInputStream("bin/dataSet.xml"));
}
///////////////////////////////////////////////
@Override
protected DatabaseOperation getSetUpOperation() throws Exception
{
return DatabaseOperation.REFRESH;
}
@Override
protected DatabaseOperation getTearDownOperation() throws Exception
{
return DatabaseOperation.NONE;
}
////////////////////////////////////////////////////
public void testSelectAccount()
{
AccountManager manager
= (AccountManager)context.getBean("accountManager");
try
{
Accountaccount
= manager.getAccount("Nick", "Marquiss", true);
assertNotNull(account);
}
catch (Exceptione)
{
logger.error(e.getMessage(),e);
}
}
public void testCreateAccount()
{
AccountManager manager
= (AccountManager)context.getBean("accountManager");
try
{
manager.createAccount("TEST", "test");
}
catch(Exception e)
{
logger.error(e.getMessage(),e);
}
}
}
在getConnection方法中,我们通过Spring配置文件获得数据连接。