使用ReflectionTestUtils解决依赖注入

时间:2023-03-10 06:38:17
使用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