【问题标题】:How to write JUnit tests for a function that is only called when the program is run?如何为仅在程序运行时调用的函数编写 JUnit 测试?
【发布时间】:2020-07-24 20:16:46
【问题描述】:

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

【问题讨论】:

标签: java unit-testing junit gui-testing gui-test-framework


【解决方案1】:

我会尝试使用 AssertJ 框架进行 Swing GUI 测试。他们有a repository with the sample projects

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

【讨论】:

    【解决方案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 部分即可测试导入逻辑。

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 2021-02-03
      • 2022-11-04
      • 1970-01-01
      相关资源
      最近更新 更多