【问题标题】:How to test java methods that works with excel with JUnit如何使用 JUnit 测试适用于 excel 的 java 方法
【发布时间】: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


    【解决方案1】:

    @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
      }
    
    }
    

    【讨论】:

    • 或者更好地更改方法签名以返回File 或文件名。在这种情况下,可以使用一些测试数据创建单元测试,使用该测试数据生成 Excel 文件,然后在单元测试中对其进行解析,并检查是否将适当的数据插入到 tan Excel 文件中的适当单元格中
    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2016-03-12
    • 2021-12-26
    相关资源
    最近更新 更多