'Junit for Files.newDirectoryStream return NullPointerException
I'm working on a Junit test which is supposed to mock Files.newDirectoryStream static method. My test files are kept in the resources folder and that's the path I'm passing to my function too.
Here is the function:
private void parseFileNames(Path dir){
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path path : stream) {
System.out.println(path.toAbsolutePath().toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
This function is giving NullPointer exception: I tried checking for:
stream.iterator() == null // This comes out to be true
Here is the Junit that I've written:
@Test
public void testDeleteExam() throws Exception {
String filePath = "C:\path\to\project\build\resources\test\sdcImagePool\RecycleBin";
PowerMockito.mockStatic(Util.class);
PowerMockito.mockStatic(File.class);
PowerMockito.mockStatic(Files.class);
PowerMockito.mockStatic(Paths.class);
Path directory = PowerMockito.mock(Path.class);
DirectoryStream<Path> directoryStream = PowerMockito.mock(DirectoryStream.class);
PowerMockito.when(Files.newDirectoryStream(Mockito.any(Path.class))).thenReturn(directoryStream);
System.setProperty("SDC_IMAGE_POOL", filePath);
IService service = Service.getInstance(Scope.SINGLETON);
File[] fls = new File(filePath + File.separator + "RecycleBin").listFiles();
List<Path> fileNames = new ArrayList<Path>();
for (File f : fls) {
fileNames.add(Paths.get(f.toURI()));
}
Iterator<Path> iterator = fileNames.stream().iterator();
PowerMockito.when(directory.iterator()).thenReturn(iterator);
String response = service.delete(filePath);
assertTrue(response.contains("204"));
}
Also, I've added this at the top:
@PrepareForTest({ UIDValidator.class, FileUtils.class, Util.class, Service.class, Files.class,
HttpClientBuilder.class, EntityUtils.class, Path.class, DirectoryStream.class })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
