Using Spring Boot 2.0.0.M5.
I need to set up an integration test which has the same context as working application but with one bean replaced by a Mockito mock.
Solved the problem easily with org.springframework.boot.test.mock.mockito.MockBean
annotated property. The thing I do not like about this solution is that now IDE says this property is never used and I agree with the warning.
How else can I mock one bean in Spring boot application test context?
I am more familiar with configuring test context in non-boot spring and @ContextConfiguration annotation, but I can't use it now because spring boot properties and other boot-related stuff stop working. So I want to keep @SpringBootTest and achieve what I want.
In reference documentation I've read that I can use @TestConfiguration:
If you want to customize the primary configuration, you can use a nested
@TestConfigurationclass. Unlike a nested@Configurationclass, which would be used instead of your application’s primary configuration, a nested@TestConfigurationclass is used in addition to your application’s primary configuration.
Tried the following code
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(initializers = FetchIntegrationTest.Initializer.class, classes = Server.class)
@Configuration
public class FetchIntegrationTest extends TestContainersAbstractTest {
@TestConfiguration
public static class NestedConfig {
@Bean
@Primary
public ScheduledSettingsFetcher scheduledSettingsFetcher() {
return Mockito.mock(ScheduledSettingsFetcher.class);
}
}
....
public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(@NonNull ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment env = configurableApplicationContext.getEnvironment();
TestPropertyValues.of("someservice.address=" + testcontainersService.getContainerIpAddress()).applyTo(env);
}
}
}
but unfortunately, it did not work out. I still have my original ScheduledSettingsFetcher instantiated instead of declared mock.
