測試結果,未執行。
I.e.如果我寫一個單元格,我現在可以從該單元格中讀取該值嗎?
另外,您向我們展示了protected
方法,您只需要測試類的公共接口。如果通過公共接口看不到結果,那麼你的課程可能會做得太多(單一責任原則)。
但是,其他考慮因素是速度和脆弱性,因爲Apache POI正在讀取和寫入實際文件,所以編寫這些測試會比較困難,而且速度會變慢。可以進行一些測試,但是如果整個套件正在讀取和寫入文件,那麼速度會變慢,並且整個測試套件在理想情況下應該在幾秒鐘內運行。
因此,我將創建一個封裝了一個Excel工作表,你想用它做什麼的接口,這可能是:
public interface StringGrid {
String readCell(int rowNum, int colNum);
void writeCell(int rowNum, int colNum, String value);
}
現在,我可能會做一個快速的實現沒有自動測試,或者只是少數圍繞Apache POI進行簡單的測試,但隨後我的套件的其餘部分將針對StringGrid
的Fake實現進行測試,並且我可以創建大量的快速運行測試,其中包含我的代碼。
所以這些可能看起來像:
真正實現,只有在它的測試和直播節目中使用。
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();
}
}
的假(一個工作,速度快,內存只有實現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方法之一,甚至谷歌表實現,你只需要添加一些測試和一個新的實現,並不需要修改任何代碼(開放封閉原則)。
你不必爲Apache POI方法進行單元測試,你只需要模擬它們。也只模擬你使用的方法不是全部 –
@KP我沒有編寫Apache POI的測試用例。我正在寫我自己的方法。 – Ashley