Search code examples
javaniojava-io

How can I test java NIO static methods?


How can I test java NIO static methods?

I have a method

public Stream<String> getFileInformation(Provider provider) {
        Path feedDirectoryPath;
        DirectoryStream<Path> stream;
        List<Path> files = new ArrayList<>();

        try {

            feedDirectoryPath = getFeedDirectoryPath();

            if (!isFileExists(feedDirectoryPath)) {
                return null;
            }

            stream = getDirectoryStream(feedDirectoryPath);

            for(Path p : stream) {
                files.add(p);
            }

            return Files.lines(Paths.get(files.stream().toString()));

        } catch (Exception e) {
            return null;
        }
    }

I have to test this method, but once my test arrives at Files.lines(..), I am stuck. I don't know how to assert this, and of-course if I were to pass a filePath like Path filePath = Paths.get("dummy.txt"); A NoSuchFileException would be thrown. Any help in testing this method would be greatly appreciated.


Solution

  • You could either supply it with an actual file (for instance in the src\test\resources folder if you're using maven), or mock the static method using PowerMock. I would recommend the first, it should be possible to load a file (for instance relative to your test class using classloader) and use this as input to the method under test.