stackerstack
stackerstack

Reputation: 265

Java unit testing Java NIO Files library?

Let's say I have a method like:

public void copyAndMoveFiles() throws IOException {
    Path source = Paths.get(path1);
    Path target = Paths.get(path2);
    if (Files.notExists(target) && target != null) {
        Files.createDirectories(Paths.get(target.toString()));
    }
    for (String fileInDirectory: Files.readAllLines(source.resolve(fileToRead))) {
        Files.copy(source.resolve(fileInDirectory), target.resolve(fileInDirectory), StandardCopyOption.REPLACE_EXISTING);          
    }
}

How would I do a unit test on this? I have tried looking at mockito but it doesn't return anything or have anything I can assert. I read about JimFs, but for some reason, I can't grasp my head around that.

Upvotes: 3

Views: 1382

Answers (1)

Mureinik
Mureinik

Reputation: 311498

I don't think mocking is the right way to go here. Since you're code reads and writes files, you need a file system, and you need to assert its state at the end of the test.

I'd create temporary directories for source and target (e.g., using JUnit's TempDir). Then, you can set up various test cases in the source directory (e.g., it's empty, one file, nested directories, etc) and at the end of the test used java.io functionality to assert the files were copied correctly.

EDIT:
stub-by example of the concept:

class MyFileUtilsTest {
    @TempDir
    File src;
    @TempDir
    File dest;

    MyFileUtils utils;

    @BeforeEach
    void setUp() {
        utils = new MyFileUtils();
    }

    @Test
    void copyAndMoveFiles() throws IOException {
        // Create a file under src, initialize the utils with src and dest
        File srcFile = File.createTempFile("myprefix", "mysuffix", src);

        utils.copyAndMoveFiles();

        File destFile = new File(dest, srcFile.getName());
        assertTrue(destFile.exists());
    }
}

Upvotes: 2

Related Questions