问题描述
我在我的代码中使用Spring注释来执行DI。所以假设我有一个依赖于另一个类class2的类class1,我将class1定义如下:
I am using Spring annotations in my code to do the DI. So lets say I have a class class1 that depends on another class class2, I define class1 as below:
@Component
public class class1 {
@Resource
private interface2 object2;
}
class2是interface2的一个实现。
class2 is an implementation of interface2.
现在假设我想模拟class2并将其传递给class1,我在class1中看不到任何构造函数或setter。我认为Spring使用反射来注入object2。我怎么嘲笑它?我应该在class1中添加一个setter吗?或者我可以像Spring一样重复使用它 - 我的意思是spring本身有一个模拟对象框架或者什么,我打算使用EasyMock进行模拟。
Now lets say I want to mock class2 and pass it to class1, I dont see any constructor or setter in class1. I think Spring uses reflection to inject object2. How can I mock it? Should I add a setter in class1? Or can I reuse the same way spring is doing it - I mean does spring itself have a mock object framework or something, I was planning to use EasyMock for the mocking.
谢谢
推荐答案
ReflectionTestUtils class 在春天可能会有帮助。
它似乎做你想要的......至少注射部分: - )
The ReflectionTestUtils class in Spring might be helpful.
It seems to do what you are looking for...at least the injection part :-)
这篇关于模拟对象和Spring注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!