I would like to reuse Spring production context configuration, but replace a few beans with another ones. If I would like to override them with a mock, I would use @MockBean
, which does exactly what I need (overrides bean), but does not allow me to configure a new bean myselves.
I know there is another way to use @ContextConfiguration
but it seems too verbose to me.
Thanks.
Bean Overriding Spring beans are identified by their names within an ApplicationContext. 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.
Spring Couldn't autowired,there is more than one bean of `` type. Bookmark this question.
You can use @SpyBean - then bean can be stubbed for specific cases (like in the case of @MockBean
), but otherwise real bean will be used.
Also, if you actually need to define custom bean definition for tests, then combination of @Primary / @Profile / @ContextConfiguration can be used for this purpose.
For example:
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration(classes = {TestConfig.class, ApplicationConfig.class})
public class ApplicatonTest {
@Profile("test")
@Configuration
static class TestConfig {
@Bean
@Primary
public SomeBean testBeanDefinition() {
SomeBean testBean = new SomeBean();
// configure SomeBean for test
return testBean;
}
}
// tests
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With