如何通过JUnit测试与excel兼容的Java方法

时间:2019-01-02 13:08:56

标签: java unit-testing automated-tests

我有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;
}

有人可以帮我还是告诉我如何开始?

1 个答案:

答案 0 :(得分:0)

@Controller bean是单例的,因此您必须避免使用可变的实例变量,例如在this.temp中存储临时文件路径。 this.temp不在请求范围内,当同时存在多个POST请求时,您当前的方法将无效。

Excel创建逻辑可能应该提取到新的@Service bean中,可以使用预定义的测试资源对其进行单元测试。

@Service
public class ExcelService {

  public OutputStream createExcel(InputStream template, List<ExcelDto> products) {
    // read InputStream
    // process template with JxlsHelper
    // return generated Excel as OutputStream
  }

}