@Test
public void createFileTest() throws Exception {
File file = new File("somefile.txt");
boolean expectedResult = true;
boolean actualResult = false;
if (file.exists()){
actualResult = true;
}
assertEquals(expectedResult, actualResult);
}
我有一个创建或重写 Json 文件的方法。 尽管文件在目录中可见,但我现在编写的测试方法无法确定该文件是否存在。
file.exists() 是如何被错误实现的,或者什么是可行的替代方案?
最佳答案
当我自己测试时,该功能似乎按我的预期工作。
如果 somefile.txt 不存在,则测试应该失败,但如果存在,则测试通过。
只是为了弄清楚构造函数和 .exists() 的作用:
File file = new File("somefile.txt");
这只是创建一个新的 File 实例,一个抽象路径名而不是实际文件。
file.exists()
javadoc 说得最好:
Tests whether the file or directory denoted by this abstract pathname exists.
如果这个测试仍然失败,我建议添加
file.getAbsoluteFile()
这将返回该文件所在的绝对路径的字符串(如果存在)。
关于java - 为什么我的 JUnit 测试文件是否存在不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41594004/