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

后端 未结 3 1775
一生所求
一生所求 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: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:

    
    
    
        
    
    
    
        
    
    

     

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

提交回复
热议问题