Hi
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 :
@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; } }
Integration test:
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = TestConfiguration.class) @WebAppConfiguration @ActiveProfiles("it") public abstract class IntegrationTest {}
TestConfiguration class:
@Configuration @Import({Application.class, MockRestTemplateConfiguration.class}) public class TestConfiguration {}
And finally MockRestTemplateConfiguration
@Configuration public class MockRestTemplateConfiguration { @Bean public RestTemplate restTemplate() { return Mockito.mock(RestTemplate.class) } }
05-08-2022 09:11 PM
Thus, bean overriding is a default behavior that happens when we define a bean within an ApplicationContext which has the same name as another bean. It works by simply replacing the former bean in case of a name conflict.
05-08-2022 11:34 PM - last edited on 05-23-2022 01:08 PM by Kh-SabW