Skip to content

Overriding beans in Integration tests

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?

This is my config file :

public class RestTemplateProvider {

    private static final int DEFAULT_SERVICE_TIMEOUT = 5_000;

    public RestTemplate restTemplate(){
        return new RestTemplate(buildClientConfigurationFactory());

    private ClientHttpRequestFactory buildClientConfigurationFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        return factory;

Integration test:

@SpringApplicationConfiguration(classes = TestConfiguration.class)
public abstract class IntegrationTest {}

TestConfiguration class:

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

And finally MockRestTemplateConfiguration

public class MockRestTemplateConfiguration {

    public RestTemplate restTemplate() {
        return Mockito.mock(RestTemplate.class)


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

Reaction on comment:

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.

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