Override a single @Configuration class on every spring boot @Test

后端 未结 3 594
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 16:19

On my spring boot application I want to override just one of my @Configuration classes with a test configuration (in particular my @EnableAuthorizationSer

3条回答
  •  死守一世寂寞
    2020-12-04 17:02

    Inner test configuration

    Example of an inner @Configuration for your test:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SomeTest {
    
        @Configuration
        static class ContextConfiguration {
            @Bean
            @Primary //may omit this if this is the only SomeBean defined/visible
            public SomeBean someBean () {
                return new SomeBean();
            }
        }
    
        @Autowired
        private SomeBean someBean;
    
        @Test
        public void testMethod() {
            // test
        }
    }
    

    Reusable test configuration

    If you wish to reuse the Test Configuration for multiple tests, you may define a standalone Configuration class with a Spring Profile @Profile("test"). Then, have your test class activate the profile with @ActiveProfiles("test"). See complete code:

    @RunWith(SpringRunner.class)
    @SpringBootTests
    @ActiveProfiles("test")
    public class SomeTest {
    
        @Autowired
        private SomeBean someBean;
    
        @Test
        public void testMethod() {
            // test
        }
    }
    
    @Configuration
    @Profile("test")
    public class TestConfiguration {
        @Bean
        @Primary //may omit this if this is the only SomeBean defined/visible
        public SomeBean someBean() {
            return new SomeBean();
        }
    }
    

    @Primary

    The @Primary annotation on the bean definition is to ensure that this one will have priority if more than one are found.

提交回复
热议问题