TestNG multithreaded test with Spring @Transactional

I use TestNG to test Spring persistent modules (JPA + Hibernate) using AbstractTransactionalTestNGSpringContextTests as a base class. All important components @Autowired, @TransactionConfiguration, @Transactional work fine.

The problem occurs when I try to run a test in parallel threads using threadPoolSize = x, invocationCount = y annotations of 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)

... Has anyone encountered this problem?

Here is the code:

@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
        }
    }
}
+3
2

, org.springframework.test.context.TestContextManager, (. https://jira.springsource.org/browse/SPR-5863)

, Transactional 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);
}

( ...)

. Spring 3.2, , !

+2

Source: https://habr.com/ru/post/1731437/


All Articles