TestNG的多线程测试与Spring @Transactional
-
18-09-2019 - |
题
我使用TestNG的测试使用AbstractTransactionalTestNGSpringContextTests作为基类的持久性Spring模块(JPA +休眠)。所有重要部件@Autowired,@TransactionConfiguration,@Transactional工作就好了。
当我试图运行在与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 )?
我面临着同样的问题,当我想启动我的事务TestNG进行并行,你可以看到Spring实际上是尝试交易绑定到正确的主题。
然而,这与这种错误的随机失败。我扩展了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);
}
(密钥被同步...)
和它现在工作就像一个魅力。我不能等待春天3.2,但这样它可以完全地parallized!