如何在集成测试中使用自定义 Bean 定义覆盖 Spring Bean



我想重用Spring生产上下文配置,但用另一个替换一些bean。如果我想用模拟覆盖它们,我会使用 @MockBean ,它完全符合我的需求(覆盖 bean(,但不允许我配置新的 bean myselves。

我知道还有另一种使用@ContextConfiguration的方法,但对我来说似乎太冗长了。

谢谢。

您可以使用

@SpyBean - 然后可以在特定情况下(例如在@MockBean的情况下(存根 bean,否则将使用真正的 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
}

最新更新