1

当我将 Junit 的 org.junit.rules.Timeout 与 spring 的基类 AbstractTransactionalJUnit4SpringContextTests 一起使用时,我得到了这个异常:

org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress

日志输出显示:

2010-07-20 09:20:16 INFO  [TransactionalTestExecutionListener.startNewTransaction] Began transaction (1): transaction manager [org.springframework.orm.jpa.JpaTransactionManager@6a1fbe]; rollback [true]
2010-07-20 09:20:16 INFO  [TransactionalTestExecutionListener.endTransaction] Rolled back transaction after test execution for test context [[TestContext@17b60b6 testClass = MyIntegrationTest, locations = array<String>['classpath:/context.xml', 'classpath:/junit-context.xml'], testInstance = MyIntegrationTest@10a4d7c, testMethod = myTest@MyIntegrationTest, testException = org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress]]

这是我的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/context.xml", "classpath:/junit-context.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class MyIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests{

    @Rule public Timeout globalTimeout = new Timeout(30000);

    @Test
    public void myTest() {
        // transactional code here saving to the database...
    }
}

但是,每当我注释掉规则时,一切正常。

我怎样才能将这两者结合在一起才能正常工作?

4

2 回答 2

0

Ahh, i worked it out. The way i solved it was to setup the transaction programatically.

@Autowired TransactionManager transactionManager;

@Test
public void test() {     
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            status.setRollbackOnly();

            // DO YOUR TEST LOGIC HERE
        }
     });
}

Hope it helps.

于 2010-07-20T09:32:20.967 回答
0

哈哈。

您也可以简单地使用 @Transactional(timeout = 30) 注释您的测试方法,超时 30 秒。这要简单得多。

于 2010-07-20T11:00:30.183 回答