Stack Overflow Asked by thePandasFriend on January 3, 2022
I have a Java program that when run, displays a GUI with a button to import a file. I want to write a unit test for the import file method to make sure the method executes all the way through, but that method is only called when the button is pressed which is by extension only available when the program is run manually. What’s the best approach for something like this?
Method to test:
public FileClass{
public Boolean import(someVar1, someVar2, someVar3){
Boolean success = false;
......
click some buttons, choose the file, and click OK
......
return success;
}
}
My junit test:
public class FileClassTest{
@Test
public void importTest(){
....
....
assertTrue(FileClass.import(x,y,z));
}
}
If you want to run a test for the logic of the import itself - it should have nothing to do with GUI at all.
So it all depends on your code - not every code is unit-testable, so you might need to refactor the needed functionality.
Consider the following "logical" refactoring to what you've presented:
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);
}
With this approach, you can test the importing logic without even thinking about the GUI part.
Answered by Mark Bramnik on January 3, 2022
I would try AssertJ framework for Swing GUI testing. They have a repository with the sample projects.
assertj-swing-junit-examples
project should be a good start.
Answered by CrazyCoder on January 3, 2022
2 Asked on December 22, 2021
1 Asked on December 22, 2021 by kyu96
1 Asked on December 22, 2021 by prawn
2 Asked on December 20, 2021 by aworeham
2 Asked on December 20, 2021
2 Asked on December 20, 2021 by fuzzyfiso
5 Asked on December 20, 2021 by p-emt
1 Asked on December 20, 2021
2 Asked on December 20, 2021 by user13953317
1 Asked on December 20, 2021 by rosalind-goh
1 Asked on December 20, 2021 by el_1988
2 Asked on December 20, 2021
1 Asked on December 20, 2021 by papelr
2 Asked on December 20, 2021
2 Asked on December 20, 2021
1 Asked on December 20, 2021 by ger-cas
0 Asked on December 20, 2021 by susanta
1 Asked on December 20, 2021 by anuj-amin
Get help from others!
Recent Questions
Recent Answers
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP