views:

136

answers:

2

When i use Junit's org.junit.rules.Timeout with spring's base class AbstractTransactionalJUnit4SpringContextTests, i get this exception:

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

The log output shows:

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]]

Here is my test:

@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...
    }
}

However whenever i comment out the rule, it all works fine.

How can i marry these two together to work correctly?

A: 

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.

JavaRocky
A: 

LOL.

You can simply also annotate your test method with @Transactional(timeout = 30) for a 30 second timeout. Which is a lot simpler.

JavaRocky