I managed to solve this issue using just Spring/JUnit (without using DBUnit).
In short, the solution was to call transactionManager.getTransaction(def).setRollbackOnly();
in @BeforeClass.
Let me first explain what I was trying to do.
My main motive was around this flow:
1. Start transaction
2. Insert load test data
3. run several test cases on the same test data
4. rollback test data.
Since I am building my load test data in @BeforeClass, I was looking to rollback in @AfterClass. This seems to be unnecessary as I can simply instruct the transaction to be rollback only in my @BeforeClass!
So here is how I did it:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/spring/applicationContext-services-test.xml")
@TestExecutionListeners(inheritListeners = false, listeners = { SpecialDependencyInjectionTestExcecutionListener.class })
@TransactionConfiguration(defaultRollback = true)
@Transactional
public class loadTest {
...
private static HibernateTransactionManager transactionManager;
...
@BeforeClass
public static void setupDB() {
//- set the transaction to rollback only. We have to get a new transaction for that.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
transactionManager.getTransaction(def).setRollbackOnly();
...
//- start loading the data using the injected services.
...
}
This helped to rollback at the end of the class.
P.S. The SpecialDependencyInjectionTestExcecutionListener
is an extension to DependencyInjectionTestExecutionListener
which I used to override beforeTestClass to force the application.context to to be loaded before calling @BeforeClass. Credit goes to Dmitriy in highlighting this Listener which was the hint to solve another problem which i had in my mind.
Thanks to everyone who helped in highlighting and suggestions which collectively led me to this solution.
Dhafir