Search code examples
javajunitjmockit

Test File Selection with JUnit/JMockit


I am attempting to test a method that returns a File object using JUnit and JMockit. I am a beginner with both of these.

The problem I am having is that I can't figure out how to properly/successfully mock the implementation method returning a file, since in reality, the user has to actually select a file for the method to return. The error I keep running into is:

java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter

Any suggestions?

Here is a recreation of my implementation:

public final class MyClass {
    public static File OpenFile(Stage stage, String title, String fileTypeText, ArrayList<String> fileType) throws Exception {
        File file = null;
        try {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle(title);
            FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionsFilter(fileTypeText + fileType, fileType);
            fileChooser.getExtensionsFilters().add(extFilter);
            file = fileChooser.showOpenDialog(stage);
            return file;
        }
        catc (Exception e) {
            if(fileType==null) {
                ...
            }
            return file;
        }
    }
}

Here is a recreation of my attempted JUnit test:

@Test
public void TestOpenFile(@Mocked Stage stage) throws Exception {

    final ArrayList<String> extensions = new ArrayList<String>();
    extensions.add(".txt");

    final File file = null;

    new Expectations() {{
        MyClass.OpenFile(stage, anyString, anyString, extensions); returns(file);
    }};

    assertEquals(file, MyClass.OpenFile(stage, "some title", "some type", extensions));

}

Solution

  • I realized that I was approaching the problem incorrectly at first. What I did to resolve this was:

    Mock the FileChooser.showOpenDialog method to return a file instead of trying to mock my own method to return a file, which would have defeated the purpose of testing.

        final File expectedFile = new File("abc");
    
        new MockUp<FileChooser>() {
    
            @Mock
            File showOpenDialog(final Window overWindow) {
                return expectedFile;
            }
        };
    
        final File actualFile = MyClass.OpenFile(...);
    
        assertEquals(expectedFile, actualFile);