簡體   English   中英

我應該為java.nio.Files創建包裝器以進行單元測試嗎?

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

我正在嘗試為下面的類編寫單元測試,而不創建真正的文件

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();
    }
}

我正在使用不能模擬靜態方法的Mockito。 所以我現在的解決方案是為java.nio.Files類編寫一個包裝類,我可以將它注入我的類,如下所示:

MyAppFileUtils類:

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);
    }
}

修改后的類是:

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();
    }
}

有人認為創建類MyAppFileUtils是多余的,因為它除了在類java.nio.Files中調用方法之外什么都不做。 你能給我一些建議嗎?

使用JimFs作為Java 7文件系統API的內存實現。 您需要確保您的代碼允許替代文件系統實現,但它應該導致更多可擴展的代碼,並且它更適合於模擬。

讓我們說你的班級看起來像

public class TempFileWriter {

    private final Path tempDir;
    private final String prefix;
    private final String suffix;

    public TempFileWriter(Path tempDir, String prefix, String suffix) {
        this.tempDir = tempDir;
        this.prefix = prefix;
        this.suffix = suffix;
    }

    public Path writeToTempFile(byte[] value) throws IOException {
        Path tempFile = Files.createTempFile(tempDir, prefix, suffix);
        Files.write(tempFile, value);
        return tempFile;
    }
}

你的單元測試可能是

@Test
public void testCreateTempFile() throws IOException {
    FileSystem fs = Jimfs.newFileSystem();

    Path tempDir = fs.getPath("mytempdir");
    String prefix = "myprefix";
    String suffix = ".tmp";

    byte[] data = new byte[1];
    data[0] = 0x66;

    TempFileWriter tempFileWriter = new TempFileWriter(tempDir, prefix, suffix);
    tempFileWriter.writeToTempFile(data);

    Files.list(tempDir).forEach(path -> {
        String fileName = path.getName(0).toString();
        assertTrue(fileName.startsWith(prefix));
        assertTrue(fileName.endsWith(suffix));
        assertTrue(Files.readAllBytes(path)[0] == 0x66)
    });
}

您的代碼現在更具擴展性,因為您可以使用不同的filesytem實現。 您的單元測試得到了改進,因為您不需要模擬任何東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM