为了账号安全,请及时绑定邮箱和手机立即绑定

如何替换@MockBean?

如何替换@MockBean?

Smart猫小萌 2021-06-18 23:22:53
是否可以@MockBean用真实的代替继承的@Bean?我有一个抽象类,它为所有 ITest 定义了许多配置和设置。仅在一次测试中,我想使用真正的 bean,而不是使用模拟的 bean。但仍然继承其余的配置。@Servicepublic 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;;}
查看完整描述

2 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

找到了一种@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

}


查看完整回答
反对 回复 2021-06-30
  • 2 回答
  • 0 关注
  • 274 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信