gpt4 book ai didi

java - 在资源文件夹下的 JUnit 测试中写入一个文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:10:16 34 4
gpt4 key购买 nike

我已经尝试过 this stack overflow question但我对 maven 有点迷茫。

在 Maven 项目中,我想测试一个最终在给定路径中写入文本文件的函数。我函数的签名是boolean printToFile(String absolutePath)(返回值是一个成功标志)

src/test/resources 下我有我想要的文件;我们称它为 expected.txt

使用 apache.commons.commons-io 依赖:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>

我想调用我的函数;创建两个 File 对象并比较它们的内容:

@Test
public void fileCreationTest() {
String outputPath = Thread.currentThread().getClass().getClassLoader().getResource("got.txt").getFile();
myTestedObject.printToFile(outputPath);
File got = new File(outputPath);

String expectedFilePath = Thread.currentThread().getClass().getClassLoader().getResource("expected.txt").getFile();
File expected = new File(expectedFilePath)

boolean areEqual = FileUtils.contentEquals(got, expected);
Assert.assertTrue(areEqual);

[编辑]
这不是调用函数的问题:如果我从普通代码调用它,它确实有效但是如果我运行我的测试,它会失败(从 maven 或我的 IDE)。我认为这与测试性质有关。

最佳答案

以下代码对我来说毫无意义(在测试或其他方面):

String outputPath = Thread.currentThread().getClass().getClassLoader().getResource("got.txt").getFile();
myTestedObject.printToFile(outputPath);
File got = new File(outputPath);

问题是 getResource 将返回一个 URL 到可能位于文件系统、JAR 或其他地方的资源。并且 getResource 必须存在才能返回非 null。这意味着您的测试需要覆盖它(并且它可能不可写)。

您可能应该做的是:

File got = File.createTempFile("got-", ".txt");
String outputPath = got.getAbsolutePath();
myTestedObject.printToFile(outputPath);

此外,对于expected 文件,我认为最好使用测试类的类加载器,而不是上下文类加载器。它也更具可读性:

String expectedFilePath = getClass().getClassLoader().getResource("expected.txt").getFile();
File expected = new File(expectedFilePath);

但是,您再次假设资源是从文件系统加载的。因此,如果不是,它可能会破裂。您可以比较来自两个 InputStream 的字节吗?

最后,确保测试使用与预期文件相同的编码写入文件,并且换行符/回车符返回匹配。

关于java - 在资源文件夹下的 JUnit 测试中写入一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898617/

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