Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rollback DB changes in @AfterClass?

I know how to configure Spring/JUnit to rollback after each test case. What I am after is a way to start and roll back one transaction for all test cases.

I am using @BeforeClass to prepare my HSQL DB for several test cases. Then I want to rollback the changes after the end of all test cases in @AfterClass.

What is the best way to achieve this rollback?

Here is my code example:

@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?
}

Any idea on the best way to do rollback in AfterClass?

Thanks to all..

like image 523
DhafirNz Avatar asked Dec 06 '25 18:12

DhafirNz


1 Answers

In case it's acceptable to you to roll back after each test and to use Spring, the following snippet from my project might help you:

@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 {
like image 138
Dmitriy Sukharev Avatar answered Dec 08 '25 09:12

Dmitriy Sukharev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!