java - Maven 单元测试 FileNotFound 错误

标签 java unit-testing maven fileoutputstream

我创建了一个 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/

相关文章:

unit-testing - 为什么我在 SonarQube 中看不到 "unit test success"小部件的 "unit tests coverage"部分

maven - Teamcity 问题 :Unable to add module to the current project as it is not of packaging type 'pom'

java - 是什么导致了这个 Maven/JBehave 错误?

Java-获取像素颜色

java - Mysql 日期/日期时间列和 Java 持久性

java - 在java中分割包含使用符号的数学函数

java - 如何使用 EasyMock 测试文件的写入/读取

C# 单元测试打开 Window.xaml

java - Jlink Spring Boot

java - getListCellRendererComponent 被调用了多少次?