使用Mockito修改Bean的依赖

概述

在使用单元测试时经常会遇到某些dependency依赖了外部资源,或者想主动绕过真正的方法执行mock返回结果而快速得到单元测试最终的期望结果,可能有以下两种场景, 对于TestCase A,设单元测试的方法是Service A的execute1方法和execute2方法,在执行execute1和execute2方法时都会调用ServiceB的不同方法,即ServiceA依赖了ServiceB;一个场景是完全对ServiceB进行Mock,如单元测试ServiceA#execute1方法时都通过Mock返回结果;一个场景是部分ServiceB的方法执行真实的业务逻辑(如查询数据库),一部分方法执行Mock返回结果,或Spy,如如单元测试ServiceA#execute2方法时,只mock ServiceB#b2结果,真正执行ServiceB#b1方法。

对TestCase的Service的依赖Bean的完全Mock

当对ServiceA的方法执行单元测试时,如ServiceA -> ServiceB,此时对ServiceB进行Mock,然后将其设置到ServiceA的属性中;后续ServiceA调用ServiceB的方法都降得到Mock后的结果;而对于ServiceB对象的本来的依赖本案暂且将其忽略,后续改进;

思路是在TestCase中依赖ServiceA的同时标示Mock ServiceB,待TestCase依赖注入完成后,新建ServiceB的Mock对象替换ServiceA中的ServiceB依赖;

@TestExecutionListeners({MockitoDependencyInjectionTestExecutionListener.class})
public class AServiceMockTest extends BaseTest {
    @Mock
    private BService bservice;
    @Autowired
    private AService aservice;
    @Before
    public void setup(){
        doReturn("mock").when(bservice).b1();
    }
    @Test
    public void test() {
        a.execute1();
    }
}
@Service
public class AServiceImpl implements AService {
    @Autowired
    private BService bservice;
     
    @Override
    public String execute1() {
        return bservice.b1(); //will return mock after Mock
    }
}

当a.execute()执行时将调用aservice的属性bservice的b1方法,返回结果就是在setup方法中指定的结果;

监听TestCase的Service的依赖Bean

当对ServiceA进行单元测试时,依赖了ServiceB,需要获取ServiceB的b1方法的真正执行结果,Mock b2方法的结果,此时可以采用Spy方式;由于ServiceA依赖了ServiceB,而这个属性可能是个AopProxy对象,并不能直接使用Mockito.mock(bservice)或者Mockito.spy(bservice),所以这里@Spy注解指定的是实现类,通过MockitoDependencyInjectionTestExecutionListener处理后,获得一个Spy对象,同时这个Spy对象设置到bservice(AopProxy对象)中去;

@TestExecutionListeners({MockitoDependencyInjectionTestExecutionListener.class})
public class AServiceMockTest extends BaseTest {
    @Spy
    private BServiceImpl bserviceImpl;
    @Autowired
    private AService aservice;
    @Before
    public void setup(){
        doReturn(true).when(bserviceImpl).b2(any(String.class));
    }
    @Test
    public void test() {
        a.execute();
    }
}
@Service
public class AServiceImpl implements AService {
    @Autowired
    private BService bservice;
     
    @Override
    public boolean execute2() {
        String str = bservice.b1();
        return bservice.b2(str);
    }
}

MockitoDependencyInjectionTestExecutionListener的实现

public class MockitoDependencyInjectionTestExecutionListener extends DependencyInjectionTestExecutionListener {

    private Set<Field> injectFields = new HashSet<>();
    private Map<String,Object> mockObjectMap = new HashMap<>();
    @Override
    protected void injectDependencies(TestContext testContext) throws Exception {
        super.injectDependencies(testContext);
        init(testContext);
    }

    /**
     * when A dependences on B
     * mock B or Spy on targetObject of bean get from Spring IoC Container whose type is B.class or beanName is BImpl
     * @param testContext
     */
    private void init(TestContext testContext) throws Exception {

        AutowireCapableBeanFactory factory =testContext.getApplicationContext().getAutowireCapableBeanFactory();
        Object bean = testContext.getTestInstance();
        Field[] fields = bean.getClass().getDeclaredFields();

        for (Field field : fields) {
            Annotation[] annotations = field.getAnnotations();
            for (Annotation annotation : annotations) {
                if(annotation instanceof Mock){
                    Class<?> clazz = field.getType();
                    Object object = Mockito.mock(clazz);
                    field.setAccessible(true);
                    field.set(bean, object);
                    mockObjectMap.put(field.getName(), object);
                } else if(annotation instanceof Spy) {
                    Object fb = factory.getBean(field.getName()); //may be a proxy that can not be spy because $Proxy is final
                    Object targetSource = AopTargetUtils.getTarget(fb);
                    Object spyObject = Mockito.spy(targetSource);
                    if (!fb.equals(targetSource)) { //proxy
                        if (AopUtils.isJdkDynamicProxy(fb)) {
                            setJdkDynamicProxyTargetObject(fb, spyObject);
                        } else { //cglib
                            setCglibProxyTargetObject(fb, spyObject);
                        }
                    } else {
                        mockObjectMap.put(field.getName(), spyObject);
                    }
                    field.setAccessible(true);
                    field.set(bean, spyObject);
                }else if (annotation instanceof Autowired){
                    injectFields.add(field);
                }
            }
        }
        for(Field field: injectFields) {
            field.setAccessible(true);
            Object fo = field.get(bean);
            if (AopUtils.isAopProxy(fo)) {
                Class targetClass = AopUtils.getTargetClass(fo);
                if(targetClass ==null)
                    return;
                Object targetSource = AopTargetUtils.getTarget(fo);
                Field[] targetFields =targetClass.getDeclaredFields();
                for(Field targetField : targetFields){
                    targetField.setAccessible(true);
                    if(mockObjectMap.get(targetField.getName()) ==null){
                        continue;
                    }
                    ReflectionTestUtils.setField(targetSource,targetField.getName(), mockObjectMap.get(targetField.getName()));
                }

            } else {
                Object realObject = factory.getBean(field.getType());
                if(null != realObject) {
                    Field[] targetFields = realObject.getClass().getDeclaredFields();
                    for(Field targetField : targetFields){
                        targetField.setAccessible(true);
                        if(mockObjectMap.get(targetField.getName()) ==null){
                            continue;
                        }
                        ReflectionTestUtils.setField(fo,targetField.getName(), mockObjectMap.get(targetField.getName()));
                    }
                }
            }
        }
    }

    private void setCglibProxyTargetObject(Object proxy, Object spyObject) throws NoSuchFieldException, IllegalAccessException {
        Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
        h.setAccessible(true);
        Object dynamicAdvisedInterceptor = h.get(proxy);
        Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
        advised.setAccessible(true);
        ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).setTarget(spyObject);

    }

    private void setJdkDynamicProxyTargetObject(Object proxy, Object spyObject) throws NoSuchFieldException, IllegalAccessException {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        AopProxy aopProxy = (AopProxy) h.get(proxy);
        Field advised = aopProxy.getClass().getDeclaredField("advised");
        advised.setAccessible(true);
        ((AdvisedSupport) advised.get(aopProxy)).setTarget(spyObject);
    }
}

maven依赖

JUnit、Mockito

AopTargetUtils

AopTargetUtils工具类参考 在spring中获取代理对象代理的目标对象工具类

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏SpiritLing

javascript 生成 uuid

全局唯一标识符(GUID,Globally Unique Identifier)也称作 UUID(Universally Unique IDentifier) ...

36070
来自专栏码匠的流水账

聊聊storm的LoggingClusterMetricsConsumer

本文主要研究一下storm的LoggingClusterMetricsConsumer

9130
来自专栏Hongten

spring开发_spring+hibernate

http://www.cnblogs.com/hongten/gallery/image/112469.html

11230
来自专栏码匠的流水账

聊聊eureka的ZoneAffinityServerListFilter

本文主要研究一下eureka的ZoneAffinityServerListFilter

10320
来自专栏别先生

Java枚举类使用和总结

12520
来自专栏Hongten

模仿Hibernate的逆向工程_java版_源码下载

在这篇blog:"Hibernate逆向工程原理_java版本"中谈到了Hibernate逆向工程原理。

19340
来自专栏算法修养

PAT 甲级 1021 Deepest Root (并查集,树的遍历)

1021. Deepest Root (25) 时间限制 1500 ms 内存限制 65536 kB 代码长度限制 16000 B ...

39170
来自专栏MasiMaro 的技术博文

windows错误处理

在调用windows API时函数会首先对我们传入的参数进行校验,然后执行,如果出现什么情况导致函数执行出错,有的函数可以通过返回值来判断函数是否出错,比如对于...

14120
来自专栏calmound

struts2+Hibernate实现用户登陆功能

实现的功能,在登陆页面输入Username和PassWord后,将username和password通过Hibernate匹对数据库是否含有一样的usernam...

35090
来自专栏码匠的流水账

聊聊storm tuple的序列化

storm-2.0.0/storm-client/src/jvm/org/apache/storm/executor/ExecutorTransfer.java

14520

扫码关注云+社区

领取腾讯云代金券