Reload or refresh a Spring application context inside a test method?

后端 未结 3 418
时光说笑
时光说笑 2020-12-05 19:50

I need to change the Spring profiles that are active in my applicationContext within a single method of my test class, and to do so I need to run one line of code before ref

3条回答
  •  星月不相逢
    2020-12-05 20:05

    There's a nice little hack to trigger a context refresh - to use org.springframework.cloud.context.refresh.ContextRefresher.

    I'm not 100% sure this method will suite you: it requires a spring-cloud-context dependency. However, this may be added just as a test dependency and not leak into production classpath.

    To use this refresher you also need to import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration configuration, which adds a RefreshScope scope to your applicationContext which is actually doing the job under the hood.

    So, modify test as follows:

    import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
    import org.springframework.cloud.context.refresh.ContextRefresher;    
    // your other imports
    
    
    @WebAppConfiguration
    @ContextConfiguration(locations = {"/web/WEB-INF/spring.xml"}, classes = RefreshAutoConfiguration.class)
    @ActiveProfiles(resolver = BaseActiveProfilesResolverTest.class)
    public class ControllerTest extends AbstractTestNGSpringContextTests {
    
        @Autowired
        private ContextRefresher contextRefresher;
    
        @Test
        public void test() throws Exception {
            // doSmth before
            contextRefresher.refresh();
            // context is refreshed - continue testing
        }
    
    }
    

提交回复
热议问题