本文介绍了在Integration测试中覆盖bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的Spring-Boot应用程序,我通过@Configuration文件提供了RestTemplate,因此我可以添加合理的默认值(ex Timeouts)。对于我的集成测试,我想模拟RestTemplate,因为我不想连接到外部服务 - 我知道期望的响应。我尝试在集成测试包中提供不同的实现,希望后者将覆盖实际的实现,但是反过来检查日志:真正的实现覆盖了测试的实现。

如何确保TestConfig中的那个是使用过的?

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 RestTemplate as I dont want to connect to external services - I know what responses to expect. I tried providing a different implementation in the integration-test package in the hope that the latter will override the real implementation , but checking the logs it`s the other way around : the real implementation overrides the test one.

How can I make sure the one from the TestConfig is the one used?

这是我的配置文件:

@Configuration
public class RestTemplateProvider {

    private static final int DEFAULT_SERVICE_TIMEOUT = 5_000;

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate(buildClientConfigurationFactory());
    }

    private ClientHttpRequestFactory buildClientConfigurationFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(DEFAULT_SERVICE_TIMEOUT);
        factory.setConnectTimeout(DEFAULT_SERVICE_TIMEOUT);
        return factory;
    }
}

整合测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
@WebAppConfiguration
@ActiveProfiles("it")
public abstract class IntegrationTest {}

TestConfiguration类:

TestConfiguration class:

@Configuration
@Import({Application.class, MockRestTemplateConfiguration.class})
public class TestConfiguration {}

最后MockRestTemplateConfiguration

And finally MockRestTemplateConfiguration

@Configuration
public class MockRestTemplateConfiguration {

    @Bean
    public RestTemplate restTemplate() {
        return Mockito.mock(RestTemplate.class)
    }
}


推荐答案

自Spring Boot 1.4以来。 x有一个选项可以使用 @MockBean 注释来伪造Spring bean。

Since Spring Boot 1.4.x there is an option to use @MockBean annotation to fake Spring beans.

评论反应:

要保留缓存中的上下文,请不要使用 @DirtiesContext ,但是使用 @ContextConfiguration(name =contextWithFakeBean)并且它将创建单独的上下文,同时它将保留默认上下文在缓存中。 Spring会在缓存中保留两个(或者你有多少个上下文)。

To keep context in cache do not use @DirtiesContext, but use @ContextConfiguration(name = "contextWithFakeBean") and it will create separate context, while it will keep default context in cache. Spring will keep both (or how many contexts you have) in cache.

我们的构建方式是这样的,大多数测试都使用默认的非流量配置,但我们有4-5个伪造的测试。默认上下文很好地重用

Our build is this way, where most of the tests are using default non-poluted config, but we have 4-5 tests that are faking beans. Default context is nicely reused

这篇关于在Integration测试中覆盖bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 14:00