[英]TestNG multithreaded test with Spring @Transactional
我正在使用TestNG來測試使用AbstractTransactionalTestNGSpringContextTests作為基類的持久性Spring模塊(JPA + Hibernate)。 所有重要的部分@Autowired,@ TransactionConfiguration,@ Transaction都可以正常工作。
當我嘗試使用threadPoolSize = x,invocationCount = y TestNG注釋在並行線程中運行測試時出現問題。
WARNING: Caught exception while allowing TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener@174202a]
to process 'before' execution of test method [testCreate()] for test instance [DaoTest] java.lang.IllegalStateException:
Cannot start new transaction without ending existing transaction: Invoke endTransaction() before startNewTransaction().
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:123)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:374)
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextBeforeTestMethod(AbstractTestNGSpringContextTests.java:146)
......有人遇到過這個問題嗎?
這是代碼:
@TransactionConfiguration(defaultRollback = false)
@ContextConfiguration(locations = { "/META-INF/app.xml" })
public class DaoTest extends AbstractTransactionalTestNGSpringContextTests {
@Autowired
private DaoMgr dm;
@Test(threadPoolSize=5, invocationCount=10)
public void testCreate() {
...
dao.persist(o);
...
}
...
更新:當所有其他測試線程沒有獲得自己的事務實例時,似乎AbstractTransactionalTestNGSpringContextTests僅為主線程維護事務。 解決這個問題的唯一方法是擴展AbstractTestNGSpringContextTests並按編程方式(而不是@Transactional注釋)為每個方法維護事務(即使用TransactionTemplate):
@Test(threadPoolSize=5, invocationCount=10)
public void testMethod() {
new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
// transactional test logic goes here
}
}
}
該事務需要在同一個線程中啟動,這里有更多細節:
Spring3 / Hibernate3 / TestNG:一些測試給出了LazyInitializationException,有些則沒有
難道你不認為這是來自org.springframework.test.context.TestContextManager不是線程安全的(參見https://jira.springsource.org/browse/SPR-5863 )?
當我想並行啟動Transactional TestNG測試時,我遇到了同樣的問題,你可以看到Spring實際上試圖將事務綁定到正確的Thread。
然而,這種錯誤隨機失敗。 我擴展了AbstractTransactionalTestNGSpringContextTests:
@Override
@BeforeMethod(alwaysRun = true)
protected synchronized void springTestContextBeforeTestMethod(
Method testMethod) throws Exception {
super.springTestContextBeforeTestMethod(testMethod);
}
@Override
@AfterMethod(alwaysRun = true)
protected synchronized void springTestContextAfterTestMethod(
Method testMethod) throws Exception {
super.springTestContextAfterTestMethod(testMethod);
}
(關鍵是同步......)
它現在像一個魅力。 我不能等到Spring 3.2,所以它可以完全平行!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.