大家好,我是神韵,是一个技术&生活博主。出文章目的主要是两个,一是好记忆不如烂笔头,记录总结中提高自己。二是希望我的文章可以帮到大家。欢迎来点赞打卡,你们的行动将是我无限的动力。
本篇主题是:单元测试踩过的坑
其它文章链接:
Unit Test 1–什么是单元测试
Unit Test 2–IDEA配置并查看单元覆盖率
Unit Test 3–编写单元测试之前需要了解的单元测试框架Mock
Unit Test 4–自动生成单元测试插件之TestMe与Diffblue
Unit Test 5–编写第一个单元测试
Unit Test 7–单元测试覆盖率表单生成交付,Jacoco的使用
1、需要测试的方法没有返回值
比如xxServe中的xxMethod方法,需要Mock它的行为可以通过一句代码搞定
Mockito.doNothing().when(xxServe).xxMethod();
这种是有返回值的:
2、针对需要调第三方服务的Service
就是通过RestTemplate去调用,代码简单可以记录如下,具体参数变动即可
@Mock
RestTemplate restTemplate;
public void testOther() {
// 制造参数
UnitTestRspDTO unitTestRspDTO = new UnitTestRspDTO();
ResponseEntity<UnitTestRspDTO> responseEntity = new ResponseEntity<>(unitTestRspDTO, HttpStatus.OK);
// 如果是三方调用,去填充参数
Mockito.when(restTemplate.postForEntity(
any(String.class),
any(HttpEntity.class),
Mockito.eq(UnitTestRspDTO.class)
)).thenReturn(responseEntity);
// 如果有unitTestService 服务类通过@Value("xxx") param参数,需要通过如下去注入
ReflectionTestUtils.setField(unitTestService, "param", "xxxUrl");
// 做真实调用 result = unitTestService.xxx()
// 参数比对 Assert.assertEquals(xx, result);
}
3、同一个方法,多次调用却失效了,请注意mock时的传参
public Integer test3(Integer param) {
UnitTestEntity unitTestEntity = unitTestRepository.findById(param).orElseThrow(() -> new RuntimeException("error"));
return param;
}
@Test
public void testTest3() throws Exception {
// 实际上模拟了,但是没生效,error
when(unitTestRepository.findById(anyInt())).thenReturn(Optional.of(new UnitTestEntity(1, "content")));
Integer result = unitTestBug.test3(null);
Assert.assertEquals(null, result);
}
因为我们穿的是null, 但是在mock时要求传的是anyInt(),这样mock造成不生效,所以需要注意你mock时的类型和你真时传参
有两种修改方法,第一是将anyInt()改成any(),或者你不传null
4.同一个类的方法怎么Mock?
参考:同一个类的方法怎么Mock?
代更新…