Java 如何为仅在程序运行时调用的函数编写JUnit测试?
我有一个Java程序,在运行时,它会显示一个GUI,带有一个按钮来导入文件。我想为import file方法编写一个单元测试,以确保该方法始终执行,但该方法仅在按下按钮时调用,而该按钮的扩展名仅在手动运行程序时可用。对于这样的事情,最好的方法是什么 测试方法:Java 如何为仅在程序运行时调用的函数编写JUnit测试?,java,unit-testing,junit,gui-testing,gui-test-framework,Java,Unit Testing,Junit,Gui Testing,Gui Test Framework,我有一个Java程序,在运行时,它会显示一个GUI,带有一个按钮来导入文件。我想为import file方法编写一个单元测试,以确保该方法始终执行,但该方法仅在按下按钮时调用,而该按钮的扩展名仅在手动运行程序时可用。对于这样的事情,最好的方法是什么 测试方法: public FileClass{ public Boolean import(someVar1, someVar2, someVar3){ Boolean success = false; ...
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));
}
}
我会尝试SwingGUI测试框架。他们有
assertj swing junit示例项目应该是一个良好的开端。我将尝试使用框架进行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部分的情况下测试导入逻辑。如果您想对导入逻辑本身运行测试,那么它应该与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部分的情况下测试导入逻辑。您需要为自动化GUI测试使用一些框架:。您需要为自动化GUI测试使用一些框架:。