I have problems getting tests to run with Transaction support.
Here is a way to reproduce:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TransactionsTest.class}, loader = AnnotationConfigContextLoader.class)
//@ContextConfiguration("classpath:applicationContext-hibernate-test.xml")
@Transactional
@Rollback
@ImportResource("classpath:applicationContext-hibernate-test.xml")
public class TransactionsTest {
@Autowired
Runnable testRunnable;
@Transactional
@Test
public void testTransactionEnabled() {
assert TransactionAspectSupport.currentTransactionStatus() != null;
}
@Test
public void testTransactionEnabledBean() {
testRunnable.run();
}
@Bean
public Runnable testRunnable() {
return new MyTransactional();
}
private static class MyTransactional implements Runnable {
@Transactional
@Override
public void run() {
assert TransactionAspectSupport.currentTransactionStatus() != null;
}
}
}
Will yield:
- testTransactionEnabled fails (EDIT: with "org.springframework.transaction.NoTransactionException: No transaction aspect-managed TransactionStatus in scope")
- testTransactionEnabledBean passes
This is despite Springs documentation clearly stating that tests annotated with @Transactional will cause tests to run within transactions:
My applicationContext-hibernate-test.xml:
<beans...>
<jdbc:embedded-database id="dataSource" type="H2" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >...
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Related question: http://ift.tt/1RxRkvW
Aucun commentaire:
Enregistrer un commentaire