如何测试REQUIRES_NEW事务

在使用spring进行集成测试时,一般会使用@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)自动回滚事务,但是如果遇到REQUIRES_NEW事务,那么这个事务是不会回滚的。

1、通过覆盖其事务传播属性来完成,即如开发环境的事务属性配置如下:

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="doReweight" propagation="REQUIRES_NEW"/>
            <tx:method name="doClear*" propagation="REQUIRES_NEW"/>
            <tx:method name="doSend*" propagation="REQUIRES_NEW"/>
            <tx:method name="doBatchSave*" propagation="REQUIRES_NEW"/>

            <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="count*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="list*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

在测试时覆盖掉即可:

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>

            <!--测试时 使用REQUIRED-->
            <tx:method name="doReweight" propagation="REQUIRED"/>
            <tx:method name="doClear*" propagation="REQUIRED"/>
            <tx:method name="doSend*" propagation="REQUIRED"/>
            <tx:method name="doBatchSave*" propagation="REQUIRED"/>

            <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="count*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="list*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

  

但是如果是@Transactional注解的事务那么就无法解决了。

2、使用spring profile测试 

还一种方式就是配置spring的profile也可以,上述配置也有点类似profile。 

3、使用我提供的工具类,在测试时移除异步支持即可。

        //移除异步支持
        if(AopProxyUtils.isTransactional(messageApi)) {
            AopProxyUtils.removeTransactional(messageApi);
        }

此工具类请参考《使用Aop工具类诊断常见问题》 

4、包级别方法测试

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void sendSystemMessage() {
      sendSystemMessageInner();
}

void sendSystemMessageInner() {
      //测试时测试这个方法即可 
}

此时测试sendSystemMessageInner即可。这种方式不管是注解还是声明都好用

其实更好的做法是spring内部提供支持,支持这样Requires_New事务的测试。

猜你喜欢

转载自jinnianshilongnian.iteye.com/blog/1901191