java 将模拟 bean 注入 spring 上下文进行测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4278788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
injecting mock beans into spring context for testing
提问by Michael Wiles
I know similar questions have been asked, e.g. here, but having done a search, I've come upon a solution I'm much happier with here
我知道有人问过类似的问题,例如这里,但是经过搜索,我找到了一个解决方案,我对这里更满意
My only problem however, is that I'm not sure how to implement this solution.
但是,我唯一的问题是我不确定如何实施此解决方案。
What I want to be able to do is via the HotswappableTargetSource override the bean definitions of select beans in my application context with my test versions and then run the test.
我想要做的是通过 HotswappableTargetSource 用我的测试版本覆盖我的应用程序上下文中选择 bean 的 bean 定义,然后运行测试。
Then for each test case I'd like to specify which beans I want to be hot swappable and then each test must be able to create its own mock versions and swap those in, and be able to swap back again.
然后对于每个测试用例,我想指定我想要热插拔的 bean,然后每个测试必须能够创建自己的模拟版本并交换它们,并且能够再次交换回来。
I am able to get the Application Context the test is running with but what I don't know is how to configure a bean to be hot swappable. I know how to do it when configuring beans with xml but I don't want to go back to using xml to configure beans.
我能够获得测试正在运行的应用程序上下文,但我不知道如何将 bean 配置为可热插拔。我知道在使用 xml 配置 bean 时该怎么做,但我不想回到使用 xml 配置 bean 的方式。
回答by Michael Wiles
UPDATE: There's a library that does it!
更新:有一个图书馆可以做到!
https://bitbucket.org/kubek2k/springockito/wiki/springockito-annotations
https://bitbucket.org/kubek2k/springockito/wiki/springockito-annotations
The solution is as follows:
解决方法如下:
You will need to change the spring context of your application to proxy the bean you want to swap:
您需要更改应用程序的 spring 上下文来代理要交换的 bean:
<bean id="beanSwappable" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="targetSource" ref="beanSwap" />
</bean>
<bean id="beanSwap" class="org.springframework.aop.target.HotSwappableTargetSource">
<constructor-arg ref="beanToSwap" />
</bean>
- beanSwap is the proxy onto this beanSwap.
- beanSwappable is the bean which you reference when you want to swap the bean
- beanToSwap is the default implementation of the bean
- beanSwap 是此 beanSwap 的代理。
- beanSwappable 是您想要交换 bean 时引用的 bean
- beanToSwap 是 bean 的默认实现
Thus a change to the system under test is necessary.
因此,有必要对被测系统进行更改。
And in your test the code will look like:
在您的测试中,代码将如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "test.xml", "spring.xml" })
public class Test {
@Resource(name="beanSwappable")
Bean b;
@Resource(name = "beanSwap")
HotSwappableTargetSource beanSwap;
public void swap() {
Bean b = << create mock version >>
beanSwap.swap(b);
// run test code which
}
}