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

Write a file in a JUnit test under resources folder

我已经尝试过 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 将 return 一个 URL 到可能位于文件系统、JAR 或其他地方的资源。并且它必须存在 getResource 到 return 非 null。这意味着您的测试需要覆盖它(并且它可能不可写)。

您可能应该做的是:

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

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

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

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

最后,确保测试写入的文件与您预期的文件具有相同的编码,并且 linefeeds/carriage return 匹配。