我使用TestNG测试持久性Spring模块(JPA+Hibernate),使用AbstractTransactionalTestNGSpringContextTests作为基类。所有重要的部分--“自动头发”、“TransactionConfiguration”、“TransactionConfiguration”--事务工作都很好。
当我试图使用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);
...
}
...
更新:当所有其他测试线程都没有得到自己的事务实例时,似乎只为主线程维护事务。解决这一问题的唯一方法是以编程方式扩展AbstractTestNGSpringContextTests并以编程方式维护事务(而不是@ transaction注释),每个方法(即使用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
}
}
}
发布于 2010-02-05 04:10:08
事务需要在同一个线程中启动,下面是更多的详细信息:
Spring3/Hibernate3/TestNG: some tests give LazyInitializationException, some don't
发布于 2012-01-05 11:07:03
您不认为这是因为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,尽管如此,它可以完全平分!
https://stackoverflow.com/questions/2202045
复制相似问题