Replace spring bean in one context with mock version from another context

谁说胖子不能爱 提交于 2019-11-30 06:57:32
Jose Luis Martin

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

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.

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);

}

You can :

  • use the Profile annotation if you have spring 3.1.
  • use the Primary annotation
  • use qualifiers
  • wire the bean yourself in the spring context

and i'm sure there are even more options.

Chandru

Create a testApplicationContext with

<beans>
    <import resource="classpath*:appContext.xml" />
    <bean id="mockbeanOfX" class=....../>
</beans>

and then load this test application context in your testcase. Now you can get the mock bean from the application context and pass it whereever needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!