2014-02-09 59 views
0

我想模擬一個JFileChooser,其中有多個文件已被選中。目前,我有一個單一的文件嘲笑。是否可以模擬文件列表?

在for循環中,selctedFiles變量尚未初始化。我想循環幾個文件。我正朝着正確的方向前進嗎?

@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()); 
    } 
} 

回答

2

根據該文檔,JFileChooser.getSelectedFiles()返回File陣列(未的File個列表)。即使它是一個列表,你也不需要嘲笑列表本身。您只需使用帶有File對象的普通列表並模擬JFileChooser即可返回該列表。但是,在這種情況下,您使用的是File陣列。

首先創建File數組:

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

然後嘲笑JFileChooser對象:

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

然後你可以通過fileChooser這樣返回的數組循環:

for (File currentFile : fileChooser.getSelectedFiles()) { 
    //... 
} 
相關問題