Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 333
stackerstack Avatar asked Aug 20 '26 03:08

stackerstack


1 Answers

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());
    }
}
like image 184
Mureinik Avatar answered Aug 22 '26 17:08

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!