我成功地使用Spring/JUnit(而不是使用DBUnit)解决了这个问题。
简而言之,在@BeforeClass中调用transactionManager.getTransaction(def).setRollbackOnly();
即可解决该问题。
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() {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
transactionManager.getTransaction(def).setRollbackOnly();
...
...
}
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