Pergunta

I'm trying to mock a JFileChooser where a number of files have been selected. At the moment I have a single file mocked.

In the for loop the selctedFiles variable hasn't been initialised. I'd like to loop several files. Am I heading in the right direction?

@Test
public void testValidateFile()
{
    String name = this.getName();
    System.out.println("Test case Name = " + name);

    JFileChooser fileChooser = mock(JFileChooser.class);
    when(fileChooser.showOpenDialog(masterView.getContentPane())).thenReturn(0);
    when(fileChooser.getSelectedFiles()).thenReturn(new File("/myImages/IMG_0037.JPG"));

    for (File currentFile : selectedFiles) {
        System.out.println(currentFile.getName());
    }
}
Foi útil?

Solução

According to the docs, JFileChooser.getSelectedFiles() returns a File array (not a list of Files). Even if it were a list, you wouldn't need to mock the list itself. You'd just use a normal list with File objects and mock the JFileChooser to return that list. In this case you use a File array, though.

First create the File array:

File[] files = { new File("f1"), new File("f2"), new File("f3") };

Then mock the JFileChooser object:

JFileChooser fileChooser = mock(JFileChooser.class);
when(fileChooser.getSelectedFiles()).thenReturn(files);

You could then loop through the array returned by fileChooser like this:

for (File currentFile : fileChooser.getSelectedFiles()) {
    //...
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top