简体   繁体   中英

Mocking file objects Mockito or Powermock?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM