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

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{
     public void importTest(){

2 Answers

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

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP