java中Jar方法的单元测试



我使用Apache POI方法在java中编写excel表。我必须对我所写的方法进行单元测试。我使用了许多Apache POI的方法。我应该截取Apache POI的不同对象类的所有方法吗?

示例:我创建了使用ApachePOI方法写入单元格的包装器方法。

protected void writeCell(int rowNum, int colNum, String value, Sheet sheet)
{
    if(value == null)
    {
        return;
    }
    Row row = sheet.getRow(rowNum);
    Cell cell = row.createCell(colNum);
    cell.setCellValue();
  }
} 

我甚至应该模拟像the Sheet.classgetRow和Row类的createCell这样的方法吗?

测试结果,而不是实现。

也就是说,如果我写一个单元格,我现在可以从那个单元格中读回那个值吗?

您还向我们展示了一个protected方法,您应该只需要测试类的公共接口。如果您不能通过公共接口看到结果,那么您的类可能做得太多了(单一责任原则)。

然而,其他考虑因素是速度和脆弱性,因为ApachePOI正在读取和写入实际文件,所以编写这些测试会有点困难,而且速度会较慢。对于一些测试来说是可以的,但如果整个套件都在读写文件,那么速度就会变慢,理想情况下,整个测试套件应该在几秒钟内运行。

所以我会创建一个封装excel表的界面,以及你想用它做什么,这可能是:

public interface StringGrid {
    String readCell(int rowNum, int colNum);
    void writeCell(int rowNum, int colNum, String value);
}

现在,我可以在没有自动测试的情况下快速实现,或者只围绕Apache POI进行一些简单的测试,但接下来我的套件的其余部分将针对StringGridFake实现进行测试,我可以围绕my代码创建大量快速运行测试。

所以这些可能看起来像:

真正的实现,仅在其测试和实时程序中使用。

public final class ApacheSheetStringGrid implements StringGrid {
    private final Sheet theApacheSheet;
    public ApacheSheetStringGrid(Sheet theApacheSheet) {
        this.theApacheSheet = theApacheSheet;
    }
    public String readCell(int rowNum, int colNum){
       ...
    }
    public void writeCell(int rowNum, int colNum, String value) {
      Row row = theApacheSheet.getRow(rowNum);
      Cell cell = row.createCell(colNum);
      cell.setCellValue();
    }
}

The Fake(StringGrid的工作、快速、仅在内存中实现),用于所有其他测试:

public final class FakeStringGrid implements StringGrid {
    private final Map<String, String> contents = new HashMap<String, String>();
    private static String getKey(int rowNum, int colNum) {
       return rowNum + ", " + colNum;
    }
    public String readCell(int rowNum, int colNum){
       return contents.get(getKey(rowNum, colNum));
    }
    public void writeCell(int rowNum, int colNum, String value) {
       contents.put(getKey(rowNum, colNum), value);
    }
}

这有额外的好处,您可以稍后将实时实现换成另一个,可能使用其他POI方法之一,甚至谷歌表单实现,您只需要添加一些测试和新的实现,并且不需要修改任何代码(开放-封闭原则)。

最新更新