注入存根服务来代替自动装配的 bean 以进行单元测试
给定这个类:
public SomeClass implements SomeInterface {
@Autowired private RemoteService rService;
}
并给定这个单元测试:
public SomeClassTest {
...
SomeClass sc = (SomeClass) ctx.getbean("someService");
..
}
我想用其他一些对象来存根“rService”。我不想修改 SomeInterface
方法来公开任何 getter/setter,因为“rService”仅适用于一种实现。
Given this class:
public SomeClass implements SomeInterface {
@Autowired private RemoteService rService;
}
And given this unit test:
public SomeClassTest {
...
SomeClass sc = (SomeClass) ctx.getbean("someService");
..
}
I want to stub the 'rService' with some other object. I do not want to have to modify the SomeInterface
method to expose any getters/setters since 'rService' only applies to just one implementation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了通过测试中的 setter 注入重置
RemoteService
的模拟/存根之外:(如果由于某种原因上述方法对您不起作用...)=>您可以创建一个“test-config.xml”,其中唯一需要重新定义的 bean 是具有相同(真实)bean 名称的
remoteService
,但具有存根实现,因此它可以覆盖真实的bean:其中
RemoteServiceStub
将扩展RemoteService
,因此可以按类型将其自动装配到SomeClass
然后在测试中,像平常一样注入 SomeClass做:
Besides just resetting the mock/stub of
RemoteService
through the setter injection within the test:(if the above does not work for you for some reason...) => you can create a "test-config.xml", where the only bean you'd redefine is
remoteService
with the same (real) bean name, but with a stub implementation, so it can override the real bean:where
RemoteServiceStub
would extend theRemoteService
, so it can be autowired by type intoSomeClass
Then in your test, inject SomeClass as you would normally do:
将 setter 添加到实现类 (
SomeClass
),并手动调用 setter。这就是依赖注入的要点,以及拥有实现和接口的优点:您可以向实现添加无法通过接口使用的方法。您不必使用 Spring 上下文来进行类的单元测试。
顺便说一句,
getBean
方法可能返回您的类的代理,而不是SomeClass
实例。Add the setter to the implementation class (
SomeClass
), and invoke the setter manually. That's the point of dependency injection, and the advantage of having an implementation and an interface : you may add methods to the implementation which won't be available through the interface.You shouldn't have to use a Spring context for the unit test of a class.
BTW, the
getBean
method probably returns a proxy to your class, and not aSomeClass
instance.