欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单元测试特殊场景代码示例

程序员文章站 2022-03-13 11:25:23
...

最近在教研发部小伙伴写单元测试发现,大部门常见的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);

 

 

 

 

 

相关标签: 单元测试 Mock