mock-hssfworkbook

xxslljrj  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(322)

我正在处理一个案例,在这个案例中,我需要为处理hssfworkbook的控制器编写单元测试。但是即使在测试类中创建了对象并将其传递给mockito之后 when/thenReturn 我仍然得到空指针异常在 wb.write(outByteStream); 控制器的。下面是我的控制器方法:

@PostMapping(value = "/recordsToExcel")
public void exportModelsHistoryDataToExcel(HttpServletRequest request,
        @RequestBody ModelsDto modelsDto) {
    int minimum = 10;

    int rand = new Random().nextInt(1000);

    int randomNum = minimum + rand;
    String excelFileName = "Revisions" + randomNum + ".xls";

    HSSFWorkbook wb = service.getModelSearchExcel(modelsDto);

    try {
        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/vnd.ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); 
        response.setHeader("Content-Disposition", "attachment; filename=" + excelFileName);
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
        outStream.close();

        wb.close();
    } catch (Exception e) {
        logger.error("ModelController - exportModelsHistoryDataToExcel() - exception::", e);
    }

}

下面是我的测试方法,我也尝试过在测试方法中创建一个工作表,但没有成功。不知道我错过了什么或做错了什么。请帮帮我!

@Test
public void testExportModelsHistoryDataToExcel() throws Exception {
     ModelsDto modelsDto = new ModelsDto();
    modelsDto.setBirthFrom("9/9/1989");
//TODO Mock objects instead of creating
    HSSFWorkbook wb = new HSSFWorkbook(); //final class can't mock
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
    wb.write(outByteStream);
    when(service.getModelSearchExcel(modelsDto)).thenReturn(wb);
    MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/recordsToExcel")
            .contentType(MediaType.APPLICATION_JSON).content(convertToJson(modelsDto));
    this.mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isOk());
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题