public void exporttoexcel(CreditHrtExchstatementQueryDTo creditHrtExchstatementqueryDTo HttpServletResponse response){ log.info("华润通积分兑换明细报表导出开始,参数--》{}",creditHrtExchstatementQueryDTO); File file =creditHrtExchStatementService.export(creditHrtExchstatementQueryDTo); String fileName = ""; try { fileName =URLEncoder.encode(file.getNameO), enc: “UTF-8").replaceall regec "\\+" replacement "%20") } catch (UnsupportedEncodingException e) { throw new BizException("文件导出错误")} try { SecureHttpUtils.exportExcel(response, file, fileName deleteFileAfterExport true); } catch (I0Exception e) { throw new BizException(“文件用出销误”:} log.info("华润通积分兑换朋细报表导出,结束“)。根据以上代码编写单元测试,需要使用mockito.lenient().when(xx).thenReturn,直接mock掉Serivice层的内容
时间: 2024-03-20 08:41:16 浏览: 116
根据您提供的代码,我可以给出一个单元测试的示例:
```
@RunWith(MockitoJUnitRunner.class)
public class CreditHrtExchStatementControllerTest {
@InjectMocks
private CreditHrtExchStatementController controller;
@Mock
private CreditHrtExchStatementService service;
@Mock
private HttpServletResponse response;
@Test
public void testExportToExcel() throws UnsupportedEncodingException, IOException {
// mock service method
File file = new File("test.xls");
Mockito.lenient().when(service.export(Mockito.any(CreditHrtExchstatementQueryDTO.class))).thenReturn(file);
// call controller method
CreditHrtExchstatementQueryDTO dto = new CreditHrtExchstatementQueryDTO();
controller.exporttoexcel(dto, response);
// verify response
Mockito.verify(response, Mockito.times(1)).setContentType("application/vnd.ms-excel");
Mockito.verify(response, Mockito.times(1)).setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(file.getName(), "UTF-8").replaceAll("\\+", "%20") + "\"");
Mockito.verify(response, Mockito.times(1)).setContentLength((int) file.length());
Mockito.verify(response.getOutputStream(), Mockito.times(1)).write(Mockito.any(byte[].class));
Mockito.verify(response.getOutputStream(), Mockito.times(1)).flush();
Mockito.verify(response.getOutputStream(), Mockito.times(1)).close();
// verify service method
Mockito.verify(service, Mockito.times(1)).export(dto);
// verify log
// ...
}
}
```
这个示例中,我们使用了 Mockito 框架来 mock 掉 Service 层的内容,然后测试 Controller 层的方法是否能够正确地将数据导出到 Excel 文件,并将文件写入 HttpServletResponse 中。在测试过程中,我们使用了 Mockito 的 verify 方法来验证方法的调用次数和参数是否正确。
阅读全文