问题
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