使用Apache POI对电子表格进行JUnit测试

时间:2013-07-15 15:43:03

标签: junit apache-poi

我正在尝试验证使用Apache POI创建的电子表格中的日期。当我执行System.out.print Date变量并且单元格内容相同时。为什么测试失败?

@Test
public void testSpreadsheetCont() throws Exception {
    Date date = new Date();
    boolean success = false;
    FileInputStream fileInputStream = new FileInputStream("File Location.xls");
    HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
    HSSFSheet worksheet = workbook.getSheetAt(0);
    HSSFRow row1 = worksheet.getRow(2);
    HSSFCell cell0 = row1.getCell(0);
    System.out.println(cell0.getDateCellValue());
    System.out.println(date);

    if (cell0.getDateCellValue() == date) {
        success = true;
    } else {
        success = false;
    }
    Assert.assertTrue(success);
}

我认为错误是我如何格式化生成电子表格的类中的日期。它的格式为("mm/dd/yyyy hh:mm")。但是当我将日期变量格式化为("mm/dd/yyyy hh:mm")并尝试比较这两个元素时,它是不成功的。

Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat("mm/dd/yyyy hh:mm");
if (cell0.getDateCellValue().toString() == ft.format(date)) {
    success = true;
} else {
    success = false;
}

2 个答案:

答案 0 :(得分:2)

使用以下进行比较。也许这可能是原因。

if(cell0.getDateCellValue().compareTo(date)==0){
    success = true;
    }else{
        success = false;
    }

答案 1 :(得分:1)

难怪它不起作用,因为你正在比较两个日期引用 - 你总会在那里得到假。