簡體   English   中英

如何為僅在程序運行時調用的 function 編寫 JUnit 測試?

[英]How to write JUnit tests for a function that is only called when the program is run?

我有一個 Java 程序,運行時會顯示一個帶有導入文件按鈕的 GUI。 我想為導入文件方法編寫一個單元測試,以確保該方法一直執行,但該方法僅在按下按鈕時調用,僅在手動運行程序時才可用。 像這樣的事情最好的方法是什么?

測試方法:

public FileClass{
    public Boolean import(someVar1, someVar2, someVar3){
        Boolean success = false;
        ......
        click some buttons, choose the file, and click OK
        ......
        return success;
    }
}

我的 junit 測試:

public class FileClassTest{
     @Test
     public void importTest(){
        ....
        ....
        assertTrue(FileClass.import(x,y,z));
     }
}

我會嘗試AssertJ框架進行 Swing GUI 測試。 他們有一個包含示例項目的存儲庫

assertj-swing-junit-examples項目應該是一個好的開始。

如果您想對導入本身的邏輯進行測試 - 它應該與 GUI 完全無關。

所以這一切都取決於您的代碼 - 並非每個代碼都是可單元測試的,因此您可能需要重構所需的功能。

考慮以下對您所呈現內容的“邏輯”重構:

public class MyGui {
    private DataImporter dataImporter;
    public MyGui(DataImporter dataImporter) {
      this.dataImporter = dataImporter;
    }
    public Boolean import(a, b, c) {
       // all UI operations here, 
       // and then when you've gathered all the data:
       byte [] dataToImport = .... 
       return dataImporter.importData(dataToImport, a,b,c);
      
    } 
}

interface DataImporter {
    /*
     * Depending on the configuration parameters a,b,c will import a stream of data identified by byte [] data (again its a schematic example). 
     * Encapsulates logic of data importing based on different parameters
     */
    boolean importData(byte [] data, a, b, c);
}

使用這種方法,您可以測試導入邏輯,甚至無需考慮 GUI 部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM