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

  • 相关阅读:
    0309. Best Time to Buy and Sell Stock with Cooldown (M)
    0621. Task Scheduler (M)
    0106. Construct Binary Tree from Inorder and Postorder Traversal (M)
    0258. Add Digits (E)
    0154. Find Minimum in Rotated Sorted Array II (H)
    0797. All Paths From Source to Target (M)
    0260. Single Number III (M)
    0072. Edit Distance (H)
    0103. Binary Tree Zigzag Level Order Traversal (M)
    0312. Burst Balloons (H)
  • 原文地址:https://www.cnblogs.com/xiaohunshi/p/5703299.html
Copyright © 2011-2022 走看看