使用JUnit4进行测试时,Spring @transactional不会启动事务

时间:2010-07-28 07:21:01

标签: java hibernate spring jpa transactions

我有以下配置。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

<bean id="dataSource" class="org.springframework.jdbc.datasource.IsolationLevelDataSourceAdapter">
    <property name="targetDataSource">
        <bean class="com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource">
            <property name="user" value="user"/>
            <property name="password" value="password"/>
            <property name="serverName" value="someserver"/>
            <property name="databaseName" value="someDBName"/>
            <property name="portNumber" value="somePortNumber"/>
        </bean>
    </property>
</bean>

<!-- this is bean is only used for data extraction module only -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" lazy-init="true">
    <property name="persistenceXmlLocation" value="classpath:persistence.xml" />
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>                
            <prop key="hibernate.format_sql">false</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <prop key="hibernate.cache.use_query_cache">true</prop>                
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<!--
    Instruct Spring to perform declarative transaction management automatically
    on annotated classes.  transaction-manager="transactionManager"
-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

然后,当我运行带有insert语句的测试时,它们会产生错误消息:

javax.persistence.TransactionRequiredException: Executing an update/delete query
    at org.hibernate.ejb.QueryImpl.executeUpdate(QueryImpl.java:47)

经过深思熟虑后,我尝试了这个:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:services.xml" })
@Transactional(propagation = Propagation.REQUIRED)
@TransactionConfiguration(defaultRollback = true)
@TestExecutionListeners(value = { DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class})
public class SimpleUnitTest {

    @Test
    public void simpleTest() throws Exception {
        System.out.println(entityManager.getTransaction().isActive());
        assertTrue(entityManager.getTransaction().isActive());
   }
}

它失败了。 entityManager.getTransaction()。isActive()实际上是假的。

为什么Transactional测试不会开始交易?

3 个答案:

答案 0 :(得分:4)

您需要添加

@TestExecutionListeners(TransactionalTestExecutionListener.class)

或从

延伸
AbstractTransactionalJUnit4SpringContextTests

获取交易行为。 (请记住,您的测试类不是bean,因此常规事务配置不适用)

答案 1 :(得分:0)

如果您使用TransactionalTestExecutionListener,则默认启用SpringJUnit4ClassRunner

您需要确保在测试上下文配置中包含事务管理配置:

@ContextConfiguration(locations = { "classpath:services.xml" })

所以你可以通过注入TM bean来检查它:

@Autowired
private PlatformTransactionManager transactionManager;

如果未解决依赖关系,则说明事务配置未正确定位。

在调试测试期间,请检查堆栈跟踪中的TransactionInterceptor

答案 2 :(得分:0)

因为您有两个与配置相关的答案,我认为问题不在于配置,而在于您如何检查事务是否处于活动状态,以及如何获取EntityManager实例。

可能存在的问题是:使用EntityManagerFactory.createEntityManager()方法而不是注入EntityManager