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

sin*_*sem 6 java spring spring-test

我想重用 Spring 生产上下文配置,但用另一个 bean 替换一些 bean。如果我想用模拟覆盖它们,我会使用@MockBean,它完全满足我的需要(覆盖 bean),但不允许我自己配置​​一个新的 bean。

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

谢谢。

Ole*_*kyi 5

您可以使用@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
}
Run Code Online (Sandbox Code Playgroud)