模拟一个班级的私人领域 [英] Mocking private field of a class

查看:92
本文介绍了模拟一个班级的私人领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课堂上有以下字段

@Resource(name = "lobIdCancellationNodeMap")
private Map<String, List<String>> lobIdCancellationNodeMap;

在此行之后,我们直接访问了此字段 lobIdCancellationNodeMap

After this line we have directly accessed this field lobIdCancellationNodeMap

我无法使用Mockito来为此设置值,并且没有可用的承包商可以设置此值。

I am not able to set value for this using Mockito, and there is no construtor available which can set this value.

lobIdCancellationNodeMap.get(lobId)

我不允许更改实现类

推荐答案

我有通过使用spring框架提供的 ReflectionTestUtils 类解决了这个问题,您可以设置该类的任何字段,而无需考虑其访问修饰符。

I have solved this problem by using ReflectionTestUtils class provided by spring framework using this you can set any field of the class irrespective of its access modifier.

ReflectionTestUtils.setField(mapper, "lobIdCancellationNodeMap", lobIdCancellationNodeMap);

这篇关于模拟一个班级的私人领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆