lundi 27 juin 2016

Should I create wrapper for java.nio.Files for Unit test purpose?

I am trying to write unit test for below class without creating real file

public class TempFileWritter{
    public String writeToTempFile(byte[] value) throws IOException {
        Path tempFile = Files.createTempFile(dir, prefix, suffix);
        Files.write(tempFile, value);
        return tempFile.toAbsolutePath().toString();
    }
}

I am using Mockito that cannot mock static method. So that my current solution is writing a wrapper class for java.nio.Files class and the I can inject it to the my class as below:

MyAppFileUtils class:

public class MyAppFileUtils {

    public void write(Path file, byte[] value) throws IOException {
        Files.write(file, value);
    }

    public Path createTempFile(Path dir, String prefix, String suffix) throws IOException {
        return Files.createTempFile(dir, prefix, suffix);
    }
}

The modified class is:

public class TempFileWritter{
    MyAppFileUtils fileUtils;
    public void setFileUtils(MyAppFileUtils fileUtils) {
        this.fileUtils = fileUtils;
    }
    public String writeToTempFile(byte[] value) throws IOException {
        Path tempFile = fileUtils.createTempFile(dir, prefix, suffix);
        fileUtils.write(tempFile, value);
        return tempFile.toAbsolutePath().toString();
    }
}

Someone agrue that creating class MyAppFileUtils is redundant because it don't do anything except calling method in class java.nio.Files. Could you give me some advices about that?

Aucun commentaire:

Enregistrer un commentaire