以下 JUnit 4 测试在 Linux 和 Windows 下运行良好:
public class TmpFileTest {
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
@Test
public void test() throws Exception {
File tmpFile = tmp.newFile();
Assert.assertEquals(tmpFile, tmpFile.getCanonicalFile());
}
}
但断言在 Mac 上失败(使用 Sierra 10.12.4 测试):
java.lang.AssertionError:
Expected :/var/folders/q4/rj3wqzms2fdcqlxgdzb3l5hc0000gn/T/junit1451860092188597816/junit1906079638039608483.tmp
Actual :/private/var/folders/q4/rj3wqzms2fdcqlxgdzb3l5hc0000gn/T/junit1451860092188597816/junit1906079638039608483.tmp
var
是指向 private/var
的符号链接(symbolic link),它通过 File#getCanonicalFile()
解析——这就是区别。
有办法解决这个问题吗?这会在我的机器上导致一堆测试失败。
最佳答案
我想您仍然需要验证两条路径是否相同。
因此,与其尝试解决 getCanonicalFile()
的工作方式(它解析符号链接(symbolic link),没有办法解决),不如接受它,在最终测试中您可以使用 getCanonicalFile()
在两端。
File expectedFile = ...
File actualFile = ...
assertEquals(expectedFile.getCanonicalFile(), tmpFile.getCanonicalFile());
那个,或者:
java.nio.file.Files.isSameFile(expectedFile.toPath(), actualFile.toPath())
关于java - Mac 上的临时文件夹和文件#getCanonicalFile(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43808602/