Use different Spring test context configuration for different test methods

后端 未结 2 1383
一整个雨季
一整个雨季 2021-02-08 01:07

We have a Spring based JUnit test class which is utilizing an inner test context configuration class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguratio         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 01:41

    With Aaron's suggestion of manually building the context I couldn't find any good examples so after spending some time getting it working I thought I'd post a simple version of the code I used in case it helps anyone else:

    class MyTest {
    
        @Autowired
        private SomeService service;
        @Autowired
        private ConfigurableApplicationContext applicationContext;
    
        public void init(Class testClass) throws Exception {
            TestContextManager testContextManager = new TestContextManager(testClass);
            testContextManager.prepareTestInstance(this);
        }
    
        @After
        public void tearDown() throws Exception {
            applicationContext.close();
        }
    
        @Test
        public void test1() throws Exception {
            init(ConfigATest.class);
            service.doSomething();
            // assert something
        }
    
        @Test
        public void test2() throws Exception {
            init(ConfigBTest.class);
            service.doSomething();
            // assert something
        }
    
        @ContextConfiguration(classes = {
            ConfigATest.ConfigA.class
        })
        static class ConfigATest {
            static class ConfigA {
                @Bean
                public SomeService someService() {
                    return new SomeService(new A());
                }
            }
        }
    
        @ContextConfiguration(classes = {
            ConfigBTest.ConfigB.class
        })
        static class ConfigBTest {
            static class ConfigB {
                @Bean
                public SomeService someService() {
                    return new SomeService(new B());
                }
            }
    
        }
    }
    

提交回复
热议问题