将模拟豆注入春天环境进行测试
问题描述:
我知道有类似的问题,例如: here,但做了搜索,我找到了一个解决方案,我很开心here将模拟豆注入春天环境进行测试
但我唯一的问题是,我不知道如何实现此解决方案。
我想要做的就是通过HotswappableTargetSource覆盖我的应用程序上下文中选择bean的bean定义与我的测试版本,然后运行测试。
然后对于每个测试用例,我想指定哪些bean想要热插拔,然后每个测试必须能够创建自己的模拟版本并交换它们,并且能够再次交换。
我能够获得测试运行的应用程序上下文,但我不知道如何配置一个bean是可热插拔的。在使用xml配置bean时我知道该怎么做,但我不想回到使用xml来配置bean。
答
更新:有一个库可以做到!
https://bitbucket.org/kubek2k/springockito/wiki/springockito-annotations
的解决方案如下:
您需要将您的应用程序的Spring上下文改为代理要交换豆:
<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是代理到这个beanSwap。
- beanSwappable是当你想换豆
- beanToSwap你引用的bean豆
因此被测改变系统是必要的默认实现。
并在测试的代码如下:
@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
}
}
但是现在有一个图书馆这样做很容易... https://bitbucket.org/kubek2k/springockito/wiki/springockito-annotations – 2012-10-05 12:41:12