简体   繁体   English

将模拟bean注入spring环境进行测试

[英]injecting mock beans into spring context for testing

I know similar questions have been asked, eg 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. 我能够获得运行测试的应用程序上下文,但我不知道如何配置bean可热插拔。 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. 我知道如何在使用xml配置bean时这样做,但我不想回到使用xml来配置bean。

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. beanSwap是这个beanSwap的代理。
  • beanSwappable is the bean which you reference when you want to swap the bean beanSwappable是您想要交换bean时引用的bean
  • beanToSwap is the default implementation of the 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

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM