简体   繁体   English

模拟文件对象是Mockito还是Powermock?

[英]Mocking file objects Mockito or Powermock?

Hw to mock the following specially the listfiles() method? 为何要专门模拟以下listfiles()方法?

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. 假设您在测试目录中有一些文件,或者添加了一些.txt或其他文件。 Then write these statements in the test class if you are using Mockito. 如果您使用的是Mockito,请在测试类中编写这些语句。 You need to add import static org.mockito.Mockito.when; 您需要添加import静态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); 这样,您告诉测试方法进入实际类的for循环中,并且可能需要编写更多一些when(thisHappens).thenReturn(givemethisresult);。 statements. 陈述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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