With Spring Boot 2.1 bean overriding is disabled by default, which is a good thing.
However I do have some tests where I replace beans with mocked instances using Mockito. With the default setting Tests with such a configuration will fail due to bean overriding.
The only way I found worked, was to enable bean overriding through application properties:
spring.main.allow-bean-definition-overriding=true
However I would really like to ensure minimal bean definition setup for my test configuration, which would be pointed out by spring with the overriding disabled.
The beans that I am overriding are either
- Defined in another configuration that imported into my test configuration
- Auto-discovered bean by annotation scanning
What I was thinking should work in the test configuration overriding the bean and slap a @Primary
on it, as we are used to for data source configurations. This however has no effect and got me wondering: Is the @Primary
and the disabled bean overriding contradictory?
Some example:
package com.stackoverflow.foo;
@Service
public class AService {
}
package com.stackoverflow.foo;
public class BService {
}
package com.stackoverflow.foo;
@Configuration
public BaseConfiguration {
@Bean
@Lazy
public BService bService() {
return new BService();
}
}
package com.stackoverflow.bar;
@Configuration
@Import({BaseConfiguration.class})
public class TestConfiguration {
@Bean
public BService bService() {
return Mockito.mock(BService.class);
}
}
@MockBean
and let Spring Boot do the replacement. So instead of@Autowired BService bService
do@MockBean BService bService
in your code. Saves you maintaining a configuration just for testing.@MockBean
in specific tests causes creating new context (instead of reusing cached one) and leads to slower tests run.