【问题标题】:Write a file in a JUnit test under resources folder在资源文件夹下的 JUnit 测试中写入文件
【发布时间】:2015-04-27 14:31:30
【问题描述】:

我已经尝试过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)。我认为这与测试性质有关。

【问题讨论】:

  • 另外,如果您手动检查文件,它们是否相同?
  • 等一下,您是说如果您在 IDE 中运行测试,它可以工作,但它不适用于 mvn test
  • 是的,这是一个错字。编辑所有这些问题(试图使其更清晰)
  • 发布您测试方法的代码。我的猜测是它有编码问题。
  • 如果你从普通代码中调用它确实有效;我保证 :) 它调用了很多与问题无关的私有函数

标签: java maven junit io


【解决方案1】:

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

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

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

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

【讨论】:

  • 实现了,有没有办法检查临时文件?
  • @manutero 当然。打印它的路径并在外部工具中打开它,或者从测试中打印它的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 2019-01-05
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 2022-09-28
  • 1970-01-01
相关资源
最近更新 更多