如何替换@MockBean?

是否可以@MockBean用真实的代替继承的@Bean?


我有一个抽象类,它为所有 ITest 定义了许多配置和设置。仅在一次测试中,我想使用真正的 bean,而不是使用模拟的 bean。但仍然继承其余的配置。


@Service

public class WrapperService {

       @Autowired

       private SomeService some;

}


@RunWith(SpringRunner.class)

@SpringBootTest(...)

public abstract class AbstractITest {

    //many more complex configurations


    @MockBean

    private SomeService service;

}


public class WrapperServiceITest extends AbstractITest {

    //usage of SomeService should not be mocked

    //when calling WrapperService


    //using spy did not work, as suggested in the comments

    @SpyBean

    private SomeService service;;

}


Smart猫小萌
浏览 275回答 2
2回答

蛊毒传说

找到了一种@Configuration在属性上使用测试条件的方法,并在 impl 中覆盖该属性@TestPropertySource:public abstrac class AbstractITest {        @TestConfiguration //important, do not use @Configuration!    @ConditionalOnProperty(value = "someservice.mock", matchIfMissing = true)    public static class SomeServiceMockConfig {        @MockBean        private SomeService some;    }}@TestPropertySource(properties = "someservice.mock=false")public class WrapperServiceITest extends AbstractITest {    //SomeService will not be mocked}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java