How do I inject a mock into the Spring context?
I would like to arrange for a Spring instance object to be a Mock instead of the normally constructed instance in order to complete an integration test.
The object being mocked is not injected by Spring into a member variable but rather is accessed by querying the Spring context. An example (for reference):
class Service {
public void doIt() {
Helper helper = new Helper();
helper.doIt();
}
}
class Helper {
public void doIt() {
BeanFactory factory = getBeanFactory(); // A function to get the bean factory
Target target = (Target)factory.getBean("target");
target.doIt();
}
}
class Target {
public void doIt() {
// Something interesting.
}
}
I would like to Mock Target in order to verify that a call to Service.doIt() calls Target.doIt().
The instance of Helper is dynamic, that is Helper is not a Spring object and only exists for a short period of time as a link between these two interfaces.
We are using a (large) spring xml file for configuration, so multiple configurations for testing is best avoided.
How can I mock Target so that the Mock is retrieved from the Spring Bean factory?
链接地址: http://www.djcxy.com/p/82054.html上一篇: 何时使用依赖注入
下一篇: 如何在Spring上下文中注入模拟?