同一个类的方法怎么Mock?spy函数啦

大家好,我是神韵,是一个技术&生活博主。出文章目的主要是两个,一是好记忆不如烂笔头,记录总结中提高自己。二是希望我的文章可以帮到大家。欢迎来点赞打卡,你们的行动将是我无限的动力。
本篇主题是:同一个类的方法怎么Mock?spy函数啦

我在测试的时候,不希望被本类的其他方法干扰,因为后面我还要单独测试其他方法,这个时候,怎么做到呢?spy函数打桩闪亮登场,待测试代码如下:
在这里插入图片描述
测试类内容,主要是spy打桩后在mock就能搞定
在这里插入图片描述

代码也放一遍
需要测试的类

@Service
public class UnitTestServices {
    @Autowired
    private UnitTestRepository unitTestRepository;

    public Map<UnitTestEntity, List<String>> queryUnitTestByContent(UnitTestEntity unitTestEntity, String... ids) {
        List<String> testList = getTestList(ids);
        UnitTestEntity content = unitTestRepository.findByContent(unitTestEntity.getContent());
        return new HashMap<UnitTestEntity, List<String>>(){{put(content, testList);}};
    }

    // 测试queryUnitTestByContent时, 不希望走这个方法
    public List<String> getTestList(String... ids) {
        return Arrays.asList(ids);
    }
}

test

@RunWith(MockitoJUnitRunner.class)
public class UnitTestServicesTest {

    @InjectMocks
    private UnitTestServices unitTestServices;
    @Mock
    private UnitTestRepository unitTestRepository;

    @Test
    public void testQueryUnitTestByContent() {
        UnitTestEntity unitTestEntity = new UnitTestEntity(1, "test");
        List<String> list = Arrays.asList("2", "3");
        // spy自己
        UnitTestServices unitTestServicesSpy = spy(unitTestServices);
        // 模拟本类方法
        doReturn(list).when(unitTestServicesSpy).getTestList(any());

        // 模拟行为--unitTestRepository.findAll(),并指定返回自己想要的结果
        Mockito.when(unitTestRepository.findByContent(any())).thenReturn(unitTestEntity);
        // 调用service方法
        Map<UnitTestEntity, List<String>> unitTestEntityListMap = unitTestServicesSpy.queryUnitTestByContent(unitTestEntity, "1", "2");
        // 校验结果
        Assert.assertEquals(list, unitTestEntityListMap.get(unitTestEntity));
    }

}

也可以通过github获取项目代码
Github link

  • 8
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值