Overriding beans in Integration tests

后端 未结 7 1911
眼角桃花
眼角桃花 2020-12-23 09:16

For my Spring-Boot app I provide a RestTemplate though a @Configuration file so I can add sensible defaults(ex Timeouts). For my integration tests I would like to mock the R

7条回答
  •  长情又很酷
    2020-12-23 09:38

    The Problem in your configuration is that you are using @Configuration for your test configuration. This will replace your main configuration. Instead use @TestConfiguration which will append (override) your main configuration.

    46.3.2 Detecting Test Configuration

    If you want to customize the primary configuration, you can use a nested @TestConfiguration class. Unlike a nested @Configuration class, which would be used instead of your application’s primary configuration, a nested @TestConfiguration class is used in addition to your application’s primary configuration.

    Example using SpringBoot:

    Main class

    @SpringBootApplication() // Will scan for @Components and @Configs in package tree
    public class Main{
    }
    

    Main config

    @Configuration
    public void AppConfig() { 
        // Define any beans
    }
    

    Test config

    @TestConfiguration
    public void AppTestConfig(){
        // override beans for testing
    } 
    

    Test class

    @RunWith(SpringRunner.class)
    @Import(AppTestConfig.class)
    @SpringBootTest
    public void AppTest() {
        // use @MockBean if you like
    }
    

    Note: Be aware, that all Beans will be created, even those that you override. Use @Profile if you wish not to instantiate a @Configuration.

提交回复
热议问题