使用ReflectionTestUtils解决依赖注入

概述

当使用junit来测试Spring的代码时,为了减少依赖,需要给对象的依赖,设置一个mock对象,但是由于Spring可以使用@Autoware类似的注解方式,对私有的成员进行赋值,此时无法直接对私有的依赖设置mock对象。可以通过引入ReflectionTestUtils,解决依赖注入的问题。

使用简介

在Spring框架中,可以使用注解的方式如:@Autowair、@Inject、@Resource,对私有的方法或属性进行注解赋值,如果需要修改赋值,可以使用ReflectionTestUtils达到目的。

代码例子

待测试类:Foo

package com.github.yongzhizhan.draftbox.springtest;

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

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 被测类
 */
public class Foo {
    @Autowired
    private String m_String;

    @PostConstruct
    private void onStarted(){
        System.out.println("on started " + m_String);
    }

    @PreDestroy
    private void onStop(){
        System.out.println("on stop " + m_String);
    }
}

使用ReflectionTestUtils解决依赖注入:

package com.github.yongzhizhan.draftbox.springtest;

import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

/**
 * 使用ReflectionTestUtils解决依赖注入
 * @author zhanyongzhi
 */
public class ReflectionTestUtilsTest {
    @Test
    public void testDefault(){
        Foo tFoo = new Foo();

        //set private property
        ReflectionTestUtils.setField(tFoo, "m_String", "Hello");

        //invoke construct and destroy method
        ReflectionTestUtils.invokeMethod(tFoo, "onStarted");
        ReflectionTestUtils.invokeMethod(tFoo, "onStop");
    }
}

在github中查看

参考

unit-testing

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,900评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,126评论 6 342
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 5,726评论 0 3
  • 哈儿,昨晚梦见你了。 我去曲靖找你,看见你了,还有你娇媚的脸庞。 当我看到你的时候,我就知道自己在做梦。我就是不想...
    xiao钱钱阅读 1,850评论 0 0
  • 一、不好意思,让一下 “同学们,今天我们班转来一位新同学,叫...叫...,呃...”班主任那七秒钟的记忆,在同学...
    璋澄阅读 1,801评论 0 0

友情链接更多精彩内容