[英]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.