【发布时间】:2019-01-02 13:08:55
【问题描述】:
我在 Java 中有一些方法可以与我尝试进行单元测试的 Excel 一起工作。 我在这里和那里尝试了一些东西,但我没有工作。
我有以下方法:
@RequestMapping(method = POST, produces = "application/vnd.ms-excel")
@ResponseBody
public ResponseEntity<byte[]> createExcel(@RequestBody List<ExcelDto> excelDtos) {
log.log(Level.INFO, "generate excel started");
try (InputStream is = GenerateExcelController.class.getResourceAsStream(PATH_TO_TEMPLATE)) {
this.temp = File.createTempFile("tempfile", ".xlsx");
try (FileOutputStream fs = new FileOutputStream(temp)) {
processExcel(excelDtos, is, fs);
return generateResponse();
}
} catch (Exception e) {
log.log(Level.SEVERE, "Cannot generate excel!", e);
}
return null;
}
private void processExcel(List<ExcelDto> productDto, InputStream is, FileOutputStream fs) throws IOException{
Context context = new Context();
context.putVar("products", productDto);
context.putVar("today", LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
JxlsHelper.getInstance().processTemplate(is, fs, context);
}
private ResponseEntity<byte[]> generateResponse() {
try (FileInputStream fileInputStream = new FileInputStream(temp.getPath())) {
Resource resource = new InputStreamResource(fileInputStream);
byte[] content = FileCopyUtils.copyToByteArray(resource.getInputStream());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
log.log(Level.INFO, "Download sample .xlsx request completed");
Files.delete(temp.toPath());
return new ResponseEntity<>(content, headers, HttpStatus.OK);
} catch (Exception e) {
log.log(Level.SEVERE, "Cannot find temp excel file!", e);
}
return null;
}
谁能帮助我或告诉我如何开始?
【问题讨论】:
标签: java unit-testing automated-tests