将一个上下文中的spring bean替换为另一上下文中的模拟版本 [英] Replace spring bean in one context with mock version from another context
问题描述
我正在编写一个集成测试,其中在启动过程中初始化了应用程序上下文xml.测试类中有几种测试方法,它们利用特定的bean'X'(已在xml中定义).我的实际要求是仅针对其中一种测试方法来模拟beanX.
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.
在一种测试方法中:我尝试使用仅带有模拟豆'M'的ClassPathXMLApplicationContext创建一个单独的应用程序上下文.
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创建的模型(具有模拟豆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.
有人可以对此有所启发吗?
Can somebody throw some light on this please?
推荐答案
没有明确的方法来替换刷新后的ApplicationContext
中的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屋!