通過(guò)AopTestUtils對(duì)切面對(duì)象進(jìn)行mock

概述

當(dāng)對(duì)一個(gè)切面類進(jìn)行測(cè)試時(shí),由于Spring對(duì)切面對(duì)象生成了proxy對(duì)象,此時(shí)對(duì)切面對(duì)象使用ReflectionTestUtils賦值,操作的是proxy對(duì)象,而不是真實(shí)對(duì)象,會(huì)使得賦值出問(wèn)題。可以通過(guò)引入AopTestUtils解決賦值問(wèn)題。

AopTestUtils使用思路

通過(guò)AopTestUtils可以通過(guò)切面proxy對(duì)象,獲取到切面的真實(shí)對(duì)象。通過(guò)使用ReflectionTestUtils對(duì)真實(shí)的切面對(duì)象修改依賴,到達(dá)mock的目的。

代碼例子

準(zhǔn)備切面對(duì)象:
IBar:

package com.github.yongzhizhan.draftbox.springtest.aop;

public interface IBar {
    String perform(String message);
}

Bar:

package com.github.yongzhizhan.draftbox.springtest.aop;

import org.springframework.beans.factory.annotation.Autowired;

public class Bar implements IBar {
    @Autowired
    Dep dep;

    @Override
    public String perform(final String message) {
        System.out.println("run bar " + message);
        return dep.perform("aspect");
    }
}

依賴對(duì)象:

package com.github.yongzhizhan.draftbox.springtest.aop;

/**
 * Dependence class
 * @author zhanyongzhi
 */
public class Dep {
    public String perform(String msg){
        return msg;
    }
}

切面:

package com.github.yongzhizhan.draftbox.springtest.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * 切面
 */
@Aspect
public class BarAspect {
    @Before(value = "execution(* com.github.yongzhizhan.draftbox.springtest.aop.Bar.perform(..))")
    public void beforeSayHello(JoinPoint vJoinPoint){
        System.out.println("aspect before "+vJoinPoint.getArgs()[0]);
    }
}

測(cè)試?yán)?/h4>
package com.github.yongzhizhan.draftbox.springtest;

import com.github.yongzhizhan.draftbox.springtest.aop.Bar;
import com.github.yongzhizhan.draftbox.springtest.aop.BarAspect;
import com.github.yongzhizhan.draftbox.springtest.aop.Dep;
import com.github.yongzhizhan.draftbox.springtest.aop.IBar;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.AopTestUtils;
import org.springframework.test.util.ReflectionTestUtils;

import static org.mockito.Mockito.when;

/**
 * 通過(guò)AopTestUtils解決ReflectionTestUtils賦值切面對(duì)象的問(wèn)題
 * @author zhanyongzhi
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:**web-config.xml")
public class AopTestUtilsTest {
    @Mock
    Dep dep;

    @Autowired
    private BarAspect barAspect;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    @InjectMocks
    IBar bar;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);

        //對(duì)象默認(rèn)返回aspect,修改為返回mock
        when(dep.perform("aspect")).thenReturn("mock");
    }

    @Test
    public void testDefault(){
        String tRet = bar.perform("hello");

        //mock注入無(wú)效,仍然返回aspect
        if(!"aspect".equals(tRet))
            Assert.fail("perform return not equeal aspect");
    }

    @Test
    public void testAopUtils(){

        //獲取真實(shí)的代理對(duì)象
        Bar tBar = AopTestUtils.getTargetObject(bar);
        ReflectionTestUtils.setField(tBar, "dep", dep);

        String tRet = bar.perform("hello");

        //此時(shí)才真正mock到
        if(!"mock".equals(tRet))
            Assert.fail("perform return not equeal mock");
    }
}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-4.1.xsd
               http://www.springframework.org/schema/mvc
               http://www.springframework.org/schema/mvc/spring-mvc.xsd
               http://www.springframework.org/schema/aop
               http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

    <!-- scan the package and the sub package -->
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.github.yongzhizhan.draftbox.springtest"/>

    <bean id="bar" class="com.github.yongzhizhan.draftbox.springtest.aop.Bar"/>
    <bean id="dep" class="com.github.yongzhizhan.draftbox.springtest.aop.Dep"/>
    <bean id="barAspect" class="com.github.yongzhizhan.draftbox.springtest.aop.BarAspect"/>

    <aop:aspectj-autoproxy/>
</beans>

在github中查看

參考

spring-aop-aspect-not-working-using-mockito
mockito-and-spring-proxies
is-it-possible-to-unproxy-a-spring-bean

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,544評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,265評(píng)論 6 342
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,643評(píng)論 18 399
  • 見(jiàn)到窗外里的林青霞,陽(yáng)光檸檬茶廣告的張柏芝,你深深的吸一口氣,對(duì)她們吹一口氣,變小變小變小。。。 于是他們就像金箍...
    三福弗朗西斯閱讀 220評(píng)論 0 0
  • 中文 鑰匙的存在由來(lái)已久。最早的鑰匙可追溯到 4000 年前,由古埃及人用木頭制成。對(duì)鑰匙做出了一些改進(jìn),改用金屬...
    西坡師妹閱讀 429評(píng)論 0 0

友情鏈接更多精彩內(nèi)容