通過AopTestUtils對切面對象進行mock

概述

當對一個切面類進行測試時觉鼻,由于Spring對切面對象生成了proxy對象挪蹭,此時對切面對象使用ReflectionTestUtils賦值,操作的是proxy對象目木,而不是真實對象溃列,會使得賦值出問題劲厌。可以通過引入AopTestUtils解決賦值問題听隐。

AopTestUtils使用思路

通過AopTestUtils可以通過切面proxy對象补鼻,獲取到切面的真實對象。通過使用ReflectionTestUtils對真實的切面對象修改依賴,到達mock的目的风范。

代碼例子

準備切面對象:
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");
    }
}

依賴對象:

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]);
    }
}

測試例子

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;

/**
 * 通過AopTestUtils解決ReflectionTestUtils賦值切面對象的問題
 * @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);

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

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

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

    @Test
    public void testAopUtils(){

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

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

        //此時才真正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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末咨跌,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子硼婿,更是在濱河造成了極大的恐慌虑润,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件加酵,死亡現場離奇詭異,居然都是意外死亡哭当,警方通過查閱死者的電腦和手機猪腕,發(fā)現死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來钦勘,“玉大人陋葡,你說我怎么就攤上這事〕共桑” “怎么了腐缤?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長肛响。 經常有香客問我岭粤,道長,這世上最難降的妖魔是什么特笋? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任剃浇,我火速辦了婚禮,結果婚禮上猎物,老公的妹妹穿的比我還像新娘虎囚。我一直安慰自己,他們只是感情好蔫磨,可當我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布淘讥。 她就那樣靜靜地躺著,像睡著了一般堤如。 火紅的嫁衣襯著肌膚如雪蒲列。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天煤惩,我揣著相機與錄音嫉嘀,去河邊找鬼。 笑死魄揉,一個胖子當著我的面吹牛剪侮,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼瓣俯,長吁一口氣:“原來是場噩夢啊……” “哼杰标!你這毒婦竟也來了?” 一聲冷哼從身側響起彩匕,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤腔剂,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后驼仪,有當地人在樹林里發(fā)現了一具尸體掸犬,經...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年绪爸,在試婚紗的時候發(fā)現自己被綠了湾碎。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡奠货,死狀恐怖介褥,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情递惋,我是刑警寧澤柔滔,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站萍虽,受9級特大地震影響睛廊,放射性物質發(fā)生泄漏。R本人自食惡果不足惜贩挣,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一喉前、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧王财,春花似錦卵迂、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至挂疆,卻和暖如春改览,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背缤言。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工宝当, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人胆萧。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓庆揩,卻偏偏與公主長得像俐东,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子订晌,可洞房花燭夜當晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理虏辫,服務發(fā)現,斷路器锈拨,智...
    卡卡羅2017閱讀 134,656評論 18 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,810評論 6 342
  • 1. Java基礎部分 基礎部分的順序:基本語法砌庄,類相關的語法,內部類的語法奕枢,繼承相關的語法娄昆,異常的語法,線程的語...
    子非魚_t_閱讀 31,631評論 18 399
  • 見到窗外里的林青霞缝彬,陽光檸檬茶廣告的張柏芝稿黄,你深深的吸一口氣,對她們吹一口氣跌造,變小變小變小。族购。壳贪。 于是他們就像金箍...
    三福弗朗西斯閱讀 196評論 0 0
  • 中文 鑰匙的存在由來已久。最早的鑰匙可追溯到 4000 年前寝杖,由古埃及人用木頭制成违施。對鑰匙做出了一些改進,改用金屬...
    西坡師妹閱讀 384評論 0 0