如果您在单元测试中使用DbUnit,您可以指定 DbUnit 应在每次测试之前执行清理和插入操作,以确保数据库的内容在每次测试之前都处于有效状态。这可以通过类似于下面的方式来完成:
@Before
public void setUp() throws Exception
{
logger.info("Performing the setup of test {}", testName.getMethodName());
IDatabaseConnection connection = null;
try
{
connection = getConnection();
IDataSet dataSet = getDataSet();
//The following line cleans up all DbUnit recognized tables and inserts and test data before every test.
DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
}
finally
{
// Closes the connection as the persistence layer gets it's connection from elsewhere
connection.close();
}
}
请注意,始终建议在@Before 设置方法中执行任何设置活动,而不是在@After 拆卸方法中。后者表明您正在正在测试的方法中创建新的数据库对象,恕我直言,这并不容易用于可测试的行为。此外,如果您在测试后进行清理,以确保第二个测试正确运行,那么任何此类清理实际上都是第二个测试设置的一部分,而不是第一个测试的拆卸。
使用 DbUnit 的替代方法是在 @Before setup 方法中启动一个新事务,并在 @After teardown 方法中回滚它。这将取决于您的数据访问层的编写方式。
如果您的数据访问层接受Connection 对象,那么您的设置例程应该创建它们,并关闭自动提交。此外,假设您的数据访问层不会调用Connection.commit。假设前面的情况,您可以在您的拆卸方法中使用Connection.rollback() 回滚事务。
关于事务控制,下面的 sn-p 演示了如何使用 JPA 来做到这一点:
@Before
public void setUp() throws Exception
{
logger.info("Performing the setup of test {}", testName.getMethodName());
em = emf.createEntityManager();
// Starts the transaction before every test
em.getTransaction.begin();
}
@After
public void tearDown() throws Exception
{
logger.info("Performing the teardown of test {}", testName.getMethodName());
if (em != null)
{
// Rolls back the transaction after every test
em.getTransaction().rollback();
em.close();
}
}
对于其他 ORM 框架甚至您的自定义持久层(如果您已经编写了一个),必须采用类似的方法。