Mocking private field of a class

柔情痞子 提交于 2019-12-14 02:36:31

问题


I have the following field in my class

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

After this line we have directly accessed this field lobIdCancellationNodeMap

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

This is how it is used

lobIdCancellationNodeMap.get(lobId)

I am not allowed to change implementation class


回答1:


While I agree with the notes by other users that it seems wrong to be testing something that isn't public-facing, I do have some sympathy for the "I am not allowed to change implementation class" situation.

The @Resource annotation is designed to be used to have the application inject an instance at runtime. I would suggest you set up your tests with a context that is similar to that of your application at runtime. This way, this class will have its resource injected.

Failing that, you could probably use Reflection to set the value to the value you require.




回答2:


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);


来源:https://stackoverflow.com/questions/22505567/mocking-private-field-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!