我创建了一个 Maven 项目,该项目涉及在完成时“写出”一个 CSV 文件。
我创建了一个测试类来生成“模拟/测试”报告文件,但是在运行单元测试时,使用“mvn package”或“mvn test”命令时,出现此错误:
28 Jan 2012 11:17:51,499 main DEBUG main.executors.ReportsExecutor:111 - Finished processing documents in 0.0 hours
28 Jan 2012 11:17:51,516 main ERROR main.utilities.FileWriterObject:279 - writeToADelimitedFile: reports/reportResults_1_28_2012_11.17.515.csv (No such file or directory) APPEND VALUE: false
28 Jan 2012 11:17:51,517 main ERROR main.executors.ReportsExecutor:170 - java.io.FileNotFoundException: reports/reportResults_1_28_2012_11.17.515.csv (No such file or directory)
java.io.FileNotFoundException: reports/reportResults_1_28_2012_11.17.515.csv (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:102)
at java.io.FileWriter.<init>(FileWriter.java:61)
at
请记住,“APPEND VALUE: false”输出只是一个调试语句,让我知道 FileWriter 构造函数中的“append” boolean 参数为 false,以便使用相应的文件名“创建”一个新文件。
现在,在生产中,它运行得很好。只是我的单元测试不起作用。是否有一些我没有配置的“根测试”目录?
我对 Maven 还很陌生。非常感谢任何反馈!
最佳答案
Maven 设置了一个名为“basedir”的属性,可以方便地在单元测试中使用。我编写了一个快速单元测试,这在 Maven 和 Eclipse 中都适用于我:
public class ReadAndWriteToTargetDirectoryTest extends Assert {
public static final String TEST_STRING = "Testing";
@Test
public void testReadWrite() {
File file = new File(System.getProperty("basedir", ".") + File.separator + "target", "mavenTest.txt");
try {
FileWriter writer = new FileWriter(file);
System.out.println("File: " + file.getCanonicalPath());
writer.write(TEST_STRING);
writer.close();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
reader.close();
assertTrue(line.equals(TEST_STRING));
} catch (IOException e) {
fail(e.getMessage());
}
}
}
当使用 System.getProperty(...) 获取“basedir”系统属性时,请务必将默认参数设置为“。”这样您也可以在 Eclipse 中运行单元测试:
System.getProperty("basedir", ".")
关于java - Maven 单元测试 FileNotFound 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9071451/