以下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
的符号链接,通过File#getCanonicalFile()
解析 - 这就是区别。
有没有办法解决这个问题?这会导致我的计算机出现大量测试失败。
答案 0 :(得分:3)
我想你仍然需要验证两条路径是否相同。
所以,不是试图解决getCanonicalFile()
如何工作(它解决了符号链接,没有解决方法),你可以接受它,在最后的测试中,你可以在两端使用getCanonicalFile()
File expectedFile = ...
File actualFile = ...
assertEquals(expectedFile.getCanonicalFile(), tmpFile.getCanonicalFile());
那,或者:
java.nio.file.Files.isSameFile(expectedFile.toPath(), actualFile.toPath())
答案 1 :(得分:2)
正如Hugues Moreau's answer所指出的,最好的办法是简单地修复测试,而不是解决给定的行为。
然而,快速入侵可以使测试通过。通过使用备用TemporaryFolder
构造函数(从JUnit 4.11开始提供;有关以前的版本,请参阅this answer),可以设置父文件夹:
@Rule
public TemporaryFolder tmp = new TemporaryFolder(System.getProperty("os.name").startsWith("Mac")
? new File("/private/" + System.getProperty("java.io.tmpdir"))
: new File(System.getProperty("java.io.tmpdir")));
使用Apache Commons Lang中的SystemUtils#IS_OS_MAC
使其更具可读性。