代码之家  ›  专栏  ›  技术社区  ›  sinedsem

如何用自定义Bean定义覆盖集成测试中的Springbean?

  •  0
  • sinedsem  · 技术社区  · 6 年前

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

    我知道还有另一种使用方法 @ContextConfiguration

    谢谢

    1 回复  |  直到 6 年前
        1
  •  5
  •   Oleksii Zghurskyi    6 年前

    你可以用 @SpyBean -然后,可以针对特定的情况(比如 @MockBean

    @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
    }