单元测试特殊场景代码示例
最近在教研发部小伙伴写单元测试发现,大部门常见的Service、DAO层的Mock大家是会的,但是一些特殊情况问问无从下手,下边巨蟹栗子:
case1:MultipartFile
被测试方法:
public String getUploadOSSUrl(String path, MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
return ossClientService.uploadBytes(path, bytes);
}
单元测试代码:
@Test
public void testGetUploadOSSUrl() throws Exception {
File file = new File("src/main/resources/application.properties");
String path = "";
MultipartFile mfile = new MockMultipartFile("haha.jpg", // 文件名
"haha.jpg", // originalName 相当于上传文件在客户机上的文件名
ContentType.APPLICATION_OCTET_STREAM.toString(), // 文件类型
new FileInputStream(file));
asyncTaskService.getUploadOSSUrl(path, mfile);
}
case2:DAO层返回Page
被测试代码:
Page<AnnouncementEntity> page =
announcementDAO.findAll(new Specification<AnnouncementEntity>(){},Pageable);
单元测试代码:
List<AnnouncementEntity> list = new ArrayList<AnnouncementEntity>();
AnnouncementEntity ae = new AnnouncementEntity();
ae.setAddTime(new Date());
list.add(ae);
Pageable pageable = new PageRequest(1, 10, Sort.Direction.DESC, "addTime");
Page<AnnouncementEntity> page = new PageImpl(list, pageable, 10);
when(announcementDAO.findAll(Mockito.any(Specification.class),Mockito.any(Pageable.class))).thenReturn(page);
上一篇: 小米手环5世界时钟怎么设置? 手环添加地区时间的技巧
下一篇: JUnit单元测试