1

我有一个 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));
     }
}
4

2 回答 2

2

如果您想对导入本身的逻辑进行测试 - 它应该与 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 部分。

于 2020-07-24T21:41:39.310 回答
2

我会尝试AssertJ框架进行 Swing GUI 测试。他们有一个包含示例项目的存储库

assertj-swing-junit-examples项目应该是一个好的开始。

于 2020-07-24T20:29:01.520 回答