【问题标题】:How to fix the code to test the case by JUnit and POI?如何修复代码以通过 JUnit 和 POI 测试案例?
【发布时间】:2017-04-20 06:27:25
【问题描述】:

为什么我不能成功测试这个案例?

@Test
public void test_Should_be_0() throws Exception {

    HSSFCell cell = new HSSFWorkbook().createSheet().createRow(0).createCell(0);
    cell.setCellValue(0);

    assertTrue(cell == 0);

感谢您的帮助。

【问题讨论】:

  • 它是如何编译的,您尝试将引用与0 进行比较,这无法确定。
  • @NicolasFilotto:谢谢你的快速回复,但是当我写 cell.setCellValue(0);我没有把值放在单元格中吗?
  • 是的,但这不是您实际测试的内容,请查看我的答案了解更多详情
  • Apache POI 附带了大量的单元测试,为什么不look at some of those and learn from them

标签: java maven junit apache-poi testcase


【解决方案1】:

我认为这是测试代码的一种方法:

1)

@Test
    public void test_Should_be_0() throws Exception {

        HSSFCell cell = new HSSFWorkbook().createSheet().createRow(0).createCell(0);
        cell.setCellValue(0);
        Assert.assertTrue(cell.getNumericCellValue() == 0);

或 2)

@Test
    public void test_Should_be_0() throws Exception {

        HSSFCell cell = new HSSFWorkbook().createSheet().createRow(0).createCell(0);
        cell.setCellValue(0);
        HSSFCell cell2 = new HSSFWorkbook().createSheet().createRow(0).createCell(0);
        cell2.setCellValue(0);
        Assert.assertTrue(cell.getNumericCellValue() == cell2.getNumericCellValue());

因为如果数字不同,则测试不起作用。

【讨论】:

  • 第二个例子是个坏主意。如果您尝试测试 setCellValue()getNumericCellValue() 并且其中一个是坏的,那么在相同的输入下它总是会以相同的方式失败。因此,如果cell.setCellValue(0)9999 放入单元格中,assertTrue(cell.getNumericCellValue() == 0) 应该会失败,因为它应该返回9999。但是如果你用setCellValue(0)设置两个单元格的值,然后用getNumericCellValue()比较结果,它们应该是相等的,你在测试2中的断言总是会通过,即使功能不好。
【解决方案2】:

您的测试assertTrue(cell == 0) 不正确,确实您尝试将对象的引用与0 进行比较,因为它们是不兼容的类型,所以如果您想检查单元格的值是否为0,您应该做这样的事情:

assertEquals(0.0, cell.getNumericCellValue(), 0.0);

【讨论】:

  • 你知道什么书可以了解如何测试 POI 单元或项目吗?
  • 有什么问题,如果我打电话:assertEquals(1, cell.getNumericCellValue(), 3); 测试再次正常工作,但这是错误的!
  • 你把值设为0,怎么可能等于1?
  • 也许我在原始代码中有错误。您的方法不适用于我的日食,但适用于我在下面发布的内容。我不知道为什么。
  • @Lost_in_the_code“你的方法不起作用”是什么意思?它有什么作用? assertEquals 的左边有一个小红 X 吗?您的导入是否正确?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
相关资源
最近更新 更多