如何使用自定义 bean 定义在集成测试中覆盖 Spring Bean?
How to override Spring Bean in integration test with custom bean definition?
我想重用 Spring 生产上下文配置,但用其他 bean 替换一些 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
}
我想重用 Spring 生产上下文配置,但用其他 bean 替换一些 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
}