是否可以在已加载的 SpringContext 中以编程方式替换 Spring Bean
我想编写一个集成测试,但有一个小限制。我有一个想要模拟的 TimeSourceBean。此 TimeSourceBean 在应用程序深处多次使用。 (无法通过反射来做到这一点)
一切都是通过自动装配完成的。
我想我可以在我的测试中加载一个额外的 XML 以及我喜欢的实现。 请参阅:此处!
但如果我可以在测试本身中创建我的模拟 TimeSourceBean 并将其注册(替换原始 bean)到上下文
=> ,那真是太好了。所以在开始测试之前,我创建模拟并注册我的 bean,如下所示:
context.registerBean(timeSourceBeanMockVersion);
如果这可能的话有什么想法吗?
I want write an integration test but with one minor restriction. I got a TimeSourceBean that I want to mock out. This TimeSourceBean is used several times deep in the application. (no way to do this with reflection)
Everything is done by autowire.
I think I could load in my test an additional XML with an implementation I like to have.
see: here!
But really nice would be when I can create my mock TimeSourceBean in the test itself and register it (replace the original bean) to the context
=> so before I start the test, I create the mock and register my bean like this:
context.registerBean(timeSourceBeanMockVersion);
Any ideas if this is possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以添加实现相同接口的其他 bean/类(希望您使用它们),并将此其他 bean 类标记为 @Primary。
但随后您需要确保该主 bean 仅在您需要的测试用例中加载。
You can add an other bean/class that implement the same interface (hopefully you use them), and mark this other bean class as @Primary.
But then you need to make sure that this primary bean is only loaded in the test cases you need them.