0

Hw to mock the following specially the listfiles()method?

File folder = new File(folderPath);
for (File fileEntry : folder.listFiles()) {
    try {
        if (StringUtils.isBlank(fileEntry.toString())) {
            throw new ConfigurationException("Sfile must be set");
        }

        String json = resourceReader.readResource(fileEntry.toString());
        try {
            config.add(parser.parseJson(json));
        } catch (Exception e) {
            LOG.error("Error in parsing json");
        }
    } catch (Exception e) {
        throw new ServiceException("Could not parse sfrom the file: " +
                fileEntry.getName(), e);
    }
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
af_khan
  • 1,030
  • 4
  • 25
  • 49
  • What is wrong with just returning some `Iterable`? What is the exact problem you encountered? – Turing85 May 19 '16 at 14:12
  • I am doing something like this. @Mock File mockFile = Mockito.mock(File.class); File[] files = {admin,database}; Mockito.when(mockFile.listFiles()).thenReturn(files); – af_khan May 19 '16 at 14:14
  • If you are using Powermock, you can get it to return a mock `File` when `new File(...)` is called. Or you could change your code to get a factory to return your file (or pass it in as a parameter, you can then pass in a mock from your unit test and mock out `listFiles`) – BretC May 19 '16 at 14:14
  • @Yahiya ... and what is wrong with your current approach? – Turing85 May 19 '16 at 14:22
  • 3
    Consider using temporary folder from junit - http://junit.org/junit4/javadoc/latest/org/junit/rules/TemporaryFolder.html – Jakub Bibro May 19 '16 at 14:36
  • 2
    What _behavior_ are you trying to test? If you mock the filesystem, you won't get a sense of whether things work with a real one. I stand by my [other SO answer here](http://stackoverflow.com/questions/17681708/mocking-files-in-java-mock-contents-mockito/17690371#17690371) that you shouldn't mock File objects as a matter of policy and practicality; instead, refactor and use an integration test with a real filesystem. – Jeff Bowman May 19 '16 at 20:19

1 Answers1

0

Let's say you have some files in test directory or add some .txt or whatever files. Then write these statements in the test class if you are using Mockito. You need to add import static org.mockito.Mockito.when; in the atest class

File f = new File("c:/test");
File[] files = f.listFiles();
when(folder.listFiles()).thenReturn(files);

By this you are telling the test method to go inside the for-loop of actual class and you may need to write some more when(thisHappens).thenReturn(givemethisresult); statements.

Arun
  • 2,312
  • 5
  • 24
  • 33