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