[英]How to override Spring Bean in integration test with custom bean definition?
我想重用Spring生产上下文配置,但是用另一个替换一些bean。 如果我想用模拟覆盖它们,则可以使用@MockBean
,它可以完全满足我的需要(覆盖bean),但不允许我自己配置新的bean。
我知道还有另一种使用@ContextConfiguration
方法,但是对我来说似乎太冗长了。
谢谢。
您可以使用@SpyBean-然后可以在特定情况下对bean进行存根(例如@MockBean
的情况),但是否则将使用真正的bean。
另外,如果您实际上需要为测试定义自定义bean定义,则可以将@Primary / @Profile / @ContextConfiguration的组合用于此目的。
例如:
@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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.