所以我有一个将字符串写入文件的方法:
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();
}
}
我的测试类具有以下 setUp 方法,该方法在每次测试之前运行(以删除每个测试之前的测试文件):
public static final String TEST_FILE = "somefile.xml";
//...
@Before
public void setUp() throws IOException {
if (MyCustomClass.fileExists(TEST_FILE)) {
new File(TEST_FILE).delete();
}
}
我的每个测试都尝试使用方法 saveStringToFile()
向文件写入内容。它成功了几次,但在某个随机点我最终得到了java.io.IOException:访问被拒绝
。不知道为什么会发生这种情况 - 有时它发生在 test1 中,有时发生在 test3 中......
当我使用 Java7 FileIO 时,它工作正常,但我需要迁移回 Java6...
最佳答案
您是否正在测试您能够创建、写入和删除文件,或者您正在测试向文件写入了什么?
如果是后者,那么也许您应该模拟/覆盖 saveStringToFile( ... )
方法,而专注于验证您正在单元测试的代码是否确实产生了正确的输出。
如果是前者,那么我非常同意@Omaha 的建议,即您的测试运行程序可能会并行运行多个测试。
希望有帮助。
关于java - JUnit 和文件写访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13473536/