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

后端 未结 3 1742
一生所求
一生所求 2020-12-30 09:36

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 specifi

相关标签:
3条回答
  • 2020-12-30 10:02

    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.

    0 讨论(0)
  • 2020-12-30 10:04

    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);
    
    }
    
    0 讨论(0)
  • 2020-12-30 10:04

    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.

    0 讨论(0)
提交回复
热议问题