为什么AOP管理的交易在我的单元测试中不起作用?

时间:2014-03-27 08:02:27

标签: spring transactions aop

我仅基于XML配置Spring。事务由Hibernate管理,我使用AOP来管理事务边界。

然而,在运行单元测试时,为什么我的AOP配置没有启动?我需要在测试方法中添加@Transactional等注释,以确保数据库操作包含在事务中,即使我已经配置了AOP来包含对事务中服务方法的调用。

为什么我的AOP配置也不适用于测试?

的applicationContext.xml

<aop:aspectj-autoproxy/>

<!-- Data Source -->
<bean id="companyDomainDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <property name="jdbcUrl" value="${jdbc.master.url}" />
    <property name="user" value="${jdbc.master.username}" />
    <property name="password" value="${jdbc.master.password}" />         
    <property name="acquireIncrement" value="1" />
    <property name="minPoolSize" value="2" />
    <property name="maxPoolSize" value="20" />
    <property name="maxIdleTime" value="4" />        
</bean>

<!-- Session Factory -->
<bean id="companyDomainSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="companyDomainDataSource"/>
    <property name="mappingResources">
        <list>
            <value>/com/company/pas/entity/mapping/partner.hbm.xml</value>
        </list>
    </property>
</bean>    

<!-- Transaction Manager -->
<bean id="companyDomainTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="companyDomainSessionFactory"/>
</bean>

<!-- Transaction Advice -->
<tx:advice id="companyDomainTransactionAdvise" transaction-manager="companyDomainTransactionManager">
    <tx:attributes>
        <!--<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>-->
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<aop:config>        
    <aop:pointcut id="serviceMethods" expression="within(com.company.pas.dao.*)"/>
    <aop:advisor advice-ref="companyDomainTransactionAdvise" pointcut-ref="serviceMethods"/>
</aop:config> 

单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
@TransactionConfiguration(transactionManager="companyDomainTransactionManager", defaultRollback=true)
public class PartnerCreateTest extends AbstractActionTest {

    @Autowired @Qualifier("createPartnerAction") AbstractAction action;

    @Test
    @Transactional
    public void testExecute() throws Exception {

        // Create partner.
        Representation rep = mock(Representation.class);
        Request req = mock(Request.class);
        Response resp = mock(Response.class);        

        when(rep.getText()).thenReturn(getContentsOf("com/company/pas/entity/xml/partner-create.xml"));
        when(req.getEntity()).thenReturn(rep);

        AbstractRequestModel crm = action.getRequestModelParser().parse(req, resp);
        action.execute(crm);

    }

}

1 个答案:

答案 0 :(得分:1)

将@Transactional添加到测试方法时,默认情况下会进行回滚。如果你不这样做,你应该预期交易会发生(他们不知道他们正在进行测试)。