ReflectionTestUtils在单元测试中的妙用
目录
ReflectionTestUtils在单元测试中的妙用
背景
在日常的代码中,单元测试是不可或缺的一环,然后很多时候我们的业务类不管是注入的字段还是写的方法都是使用private修饰符修饰的,这导致我们没有办法方便的进行单元测试,本文就简答介绍下如何通过spring自带的ReflectionTestUtils工具类来测试私有字段和测试私有方法实现
技术实现
ReflectionTestUtils是spring框架的一个非常有用的测试工具类,他的setField方法可以方便的设置类的私有成员对象,invokeMethod方法则可以方便的测试类的私有方法,下面我们结合mockito单元测试框架+ReflectionTestUtils来看一下简单实现的例子,首先这个是要被测试的用户业务类:
@Component("userBisiness")
public class UserBisiness{
@Autowired
private ConfigService configService;
private boolean isOffline(Integer salesNo) {
if(salesNo %2 ==0){
return true;
}
return false;
}
private String getVersion() {
List<String> configs = configService.getConfig(UserType.inner);
if (ListUtil.isEmpty(configs)) {
return null;
}
return configs.get(0);
}
}
业务类依赖的外部服务类ConfigService类如下:
public interface ConfigService {
List<String> getConfig(String type);
我们目的是为了测试UserBisiness的两个私有方法,由于其中一个私有方法还依赖另一个外部服务ConfigService,所以我们还要模拟这个外部接口类的返回来进行测试:
@Test
public void testCallPrivateMethod() {
MockitoAnnotations.initMocks(this);
String result = ReflectionTestUtils.invokeMethod(userBisiness, "getVersion");
System.out.println(result);
boolean result1 =
ReflectionTestUtils.invokeMethod(userBisiness, "isOffline", 100);
System.out.println(result1);
}
@Test
public void testSetPrivateField() {
MockitoAnnotations.initMocks(this);
String result = ReflectionTestUtils.invokeMethod(userBisiness, "getVersion");
System.out.println(result);
ConfigService mockConfigService = Mockito.mock(ConfigService.class);
Mockito.doReturn(Lists.newArrayList()).when(mockConfigService).getConfig(Mockito.any());
ReflectionTestUtils.setField(userBisiness, "configService", mockConfigService);
String result_mock = ReflectionTestUtils.invokeMethod(userBisiness, "getVersion");
System.out.println(result_mock);
}
这样我们就可以测试私有的方法和字段了
小结
ReflectionTestUtils工具类非常有用,可以设置私有成员变量的值,可以调用类的私有成员方法,这在单元测试中用处极大