Java JUnit和文件写入访问

Java JUnit和文件写入访问,java,file,junit,ioexception,Java,File,Junit,Ioexception,因此,我有一个方法将字符串写入文件: public static void saveStringToFile(String path, String string) { File file = new File(path); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStac

因此,我有一个方法将字符串写入文件:

 public static void saveStringToFile(String path, String string) {

    File file = new File(path);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    FileWriter out = null;
    try {
        out = new FileWriter(path);
        out.write(string);
        if (out != null) {
            out.close();
        }
    } catch (FileNotFoundException e) {

        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }

}
以及我的测试类,该类使用以下在每次测试之前运行的设置方法(在每次测试之前删除测试文件):

//

我的每个测试都尝试使用方法
saveStringToFile()
向文件写入内容。它成功了好几次,但我最终得到了
java.io.IOException:Access被拒绝了
。不知道为什么会发生这种情况-有时在test1中发生,有时在test3中发生


当我使用Java7 FileIO时,它工作正常,但我需要迁移回Java6…

您是在测试您是否能够创建、写入和删除文件,还是在测试写入文件的内容

如果是后者,那么您可能应该模拟/重写
saveStringToFile(…)
方法,而应该专注于验证正在进行单元测试的代码是否实际生成了正确的输出

如果是前者,那么我非常同意@Omaha的建议,即您的测试运行者可能同时运行多个测试


希望这能有所帮助。

所以,JUnit可能没有并行运行,因为我认为它在默认情况下不会运行

问题出在我的
readfile
方法中:

private String readFile(String path) throws FileNotFoundException {
    return (new Scanner(new File(path))).useDelimiter("\\Z").next();
}
为了工作得好,我必须修好

private String readFile(String path) throws FileNotFoundException {
    Scanner scanner = (new Scanner(new File(path)));
    String s = scanner.useDelimiter("\\Z").next();
    scanner.close();
    return s;
}

Scanner的
close()
方法是关键…

异常处理存在一些问题。对
out.close()
的调用应该在finally块中的一个单独的try-catch块中。如果写入文件时引发异常,则该文件永远不会关闭


我建议您看看ApacheCommons IO之类的东西,它有许多有用的IO方法,比如
FileUtils.writeStringToFile()

您是如何执行测试的?是否可能您的测试运行程序正在并行运行它们,并且测试在尝试访问该文件时相互重叠?添加同步块。我正在使用Eclipse>Run as JUnit test运行它。。。由于怀疑测试可能在Parralel中运行-我如何验证这一点以及我可以用它做什么?请参阅下面的答案,您不应该对文件系统或测试运行程序并行性进行单元测试:-)
private String readFile(String path) throws FileNotFoundException {
    return (new Scanner(new File(path))).useDelimiter("\\Z").next();
}
private String readFile(String path) throws FileNotFoundException {
    Scanner scanner = (new Scanner(new File(path)));
    String s = scanner.useDelimiter("\\Z").next();
    scanner.close();
    return s;
}