用另一个上下文中的模拟版本替换一个上下文中的 spring bean [英] Replace spring bean in one context with mock version from another context

查看:34
本文介绍了用另一个上下文中的模拟版本替换一个上下文中的 spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个集成测试,其中应用程序上下文 xml 在启动期间被初始化.测试类中有几种测试方法,它们使用特定的 bean 'X'(已经在 xml 中定义).我的实际要求是仅针对其中一种测试方法模拟 bean X.

I'm writing an integration test where an application context xml is initialized during startup. There are several test methods in the test class which make use of a specific bean 'X'(already defined in the xml). My actual requirement is to mock bean X only for one of the test methods.

在测试方法中:我尝试使用 ClassPathXMLApplicationContext 创建一个单独的应用程序上下文,其中只有模拟 bean 'M'.

Inside a test method: I tried creating a separate application context using ClassPathXMLApplicationContext with only the mock bean 'M'.

现在我有两个应用程序上下文 (AC):1. 在测试用例启动期间创建的一个(包含实际的 bean X)和2. 在测试方法中使用 ClassPathXMLApplicationContext 创建的一个(具有模拟 bean M).

Now I have two Application Contexts (AC): 1. One created during test case startup (which contains the actual bean X) and 2. One created using ClassPathXMLApplicationContext within the test method (which has the mock bean M).

我想使用 AC:2 中的模拟 bean 定义M"替换 AC:1 中的实际 bean 定义X".

I want to replaced the actual bean definition 'X' within AC:1, using the mock bean definition 'M' from AC:2.

有人可以解释一下吗?

推荐答案

没有明确的方法可以在刷新的 ApplicationContext 中替换 aa bean,除非你关闭它并再次刷新它.

There is not a clear way to replace a a bean in a refreshed ApplicationContext unless you close it and refresh it again.

要模拟它,常用的方法是使用要替换的 bean 的 Proxy 并在运行时更改目标.

To emulate it, the common approach is to use a Proxy of the bean that you want to replace and change the target at runtime.

您可以使用框架 aop 支持类轻松做到这一点:

You can do it easily using the framework aop support classes:

<bean id="realBean" class="RealClass" />
<bean id="mockBean" class="MockClass" />
<bean id="targetSource" class="org.springframework.aop.target.HotSwappableTargetSource">
    <constructor-arg ref="realBean" />
</bean>

<bean id="bean" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="targetSource" ref="targetSource" />
</bean>

 

@Test
public void testWithMockBean() {
Object real = targetSource.swap(mock);
....
// do your test work
...
targetSource.swap(real);

}

这篇关于用另一个上下文中的模拟版本替换一个上下文中的 spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆