zoukankan      html  css  js  c++  java
  • 使用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

  • 相关阅读:
    20200929-git地址
    20200917-1 每周例行报告
    20200917-2 词频统计
    20200917-3 白名单
    20200910-1 每周例行报告
    20200910-2 博客作业
    20200924-3 单元测试,结对
    20200924-2 功能测试
    20200924-5 四则运算试题生成,结对
    20200924-4 代码规范,结对要求
  • 原文地址:https://www.cnblogs.com/xiaohunshi/p/5703299.html
Copyright © 2011-2022 走看看