gpt4 book ai didi

Java 单元测试 Java NIO 文件库?

转载 作者:行者123 更新时间:2023-12-04 14:50:21 26 4
gpt4 key购买 nike

假设我有这样的方法:

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

我将如何对此进行单元测试?我试过查看 mockito,但它没有返回任何内容,也没有我可以断言的任何内容。我读到了 JimFs,但出于某种原因,我无法理解它。

最佳答案

我不认为 mock 是正确的方式。由于您是代码读取和写入文件,因此需要一个文件系统,并且需要在测试结束时断言其状态。

我会为源和目标创建临时目录(例如,使用 JUnit 的 TempDir )。然后,您可以在源目录中设置各种测试用例(例如,它是空的、一个文件、嵌套目录等),并在测试结束时使用 java.io 功能来断言文件已正确复制。

编辑:
stub-by概念的例子:

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

关于Java 单元测试 Java NIO 文件库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69170117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com