如何在@AfterClass中回滚数据库更改?

Dha*_*rNz 3 java junit rollback

我知道如何配置Spring/JUnit以在每个测试用例后回滚.我所追求的是一种为所有测试用例启动和回滚一个事务的方法.

我正在使用@BeforeClass为几个测试用例准备我的HSQL数据库.然后我想在@AfterClass中的所有测试用例结束后回滚更改.

实现此回滚的最佳方法是什么?

这是我的代码示例:

@BeforeClass
public static void setupDB(){
ApplicationContext context = new ClassPathXmlApplicationContext(
        "classpath:/spring/applicationContext-services-test.xml");
//- get beans and insert some records to the DB
...
}

@AfterClass
public static void cleanUp(){
   ??? what should go here?
}
Run Code Online (Sandbox Code Playgroud)

有关在AfterClass中进行回滚的最佳方法的任何想法吗?

谢谢大家..

Dmi*_*rev 5

如果您在每次测试后回滚并使用Spring是可以接受的,那么我项目中的以下代码段可能对您有所帮助:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/net/sukharevd/shopzilla/model/application-context-dao.xml" })
@TestExecutionListeners(DependencyInjectionTestExecutionListener.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class HibernateCategoryDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
Run Code Online (Sandbox Code Playgroud)