1 year ago

#343621

test-img

devCodePro

How to mock file, java.nio.Path, Paths?

I have a method that has a few static classes as well as java.nio.Files,ResourceUtils, etc I am not sure how to write test cases for it as I keep getting NPE Paths.get(filePath);

Below is the method:

@Value("${file.path}")
private String filePath;
private List<MyJsonObj> readJSONFiles() throws IOException {
    List<MyJsonObj> myJsonObjList = new ArrayList<>();
    Gson gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
    Path folder = Paths.get(filePath);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder)) {
        for (Path entry : stream) {
        String file = folder + "\\" + entry.getFileName().toString();
        MyJsonObj jsonObj = gson.fromJson(new FileReader(ResourceUtils.getFile(file)), MyJsonObj.class);

        myJsonObjList.add(jsonObj);

        }
    return myJsonObjList;
}catch (IOException e) {
         logger.error(Arrays.asList(e.getStackTrace()).toString());

    }
}

java

unit-testing

junit

mockito

powermock

0 Answers

Your Answer

Accepted video resources