JUnit规则TemporaryFolder会任意抛出IOException异常。

9

我在这里遇到了一个奇怪的问题...

我有一个实现了几个测试的JUnit。这个类看起来像下面这样:

public class MyTest {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void myTest1() throws IOException {
        String destinationPath = folder.newFile("destination1.txt").getPath();
        // Do things
    }

    @Test
    public void myTest2() throws IOException {
        String destinationPath = folder.newFile("destination2.txt").getPath();
        // Do things
    }

    @Test
    public void myTest3() throws IOException {
        String destinationPath = folder.newFile("destination.txt").getPath();
        // Do things
    }
}

这个测试类在我以前的环境中运行良好,并且在 Continuum 中仍然可以正常工作。

然而,当从 Eclipse 启动时,一些或全部测试会随机抛出 IOException,例如:

java.io.IOException: The system cannot find the path specified
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:883)
    at org.junit.rules.TemporaryFolder.newFile(TemporaryFolder.java:53)
    at MyTest.myTest2(MyTest.java:50)

我遇到了完全相同的问题,在运行JUnit 4.9或JUnit 4.10时...

我该如何修复它,使其正常工作?


应该可以。你是用哪种“Runner”来运行测试的?它们是并发的吗?您可能需要进行更多调试,例如在问题发生时也将“folder”变量打印输出以查看其指向何处。 - Petr Janeček
你能说一下你在测试中做了什么吗?你是在写文件吗?另外,你的Windows索引是否正在运行? - Matthew Farwell
是的,该程序的目的是处理数据并将文件作为输出写入。没有运行Windows索引。 - Jean Logeart
3个回答

1

您应该尝试禁用您的反病毒保护。

我曾经遇到过同样的问题,禁用卡巴斯基之后一切都正常了。


0
看起来,这可能更多是与Windows相关的问题,而不是JUnit的问题。以某种方式,您可能在以“受限制的权限用户”身份登录时缺少创建文件夹/文件的权限。
我猜您可以尝试像JUnit一样创建一个临时文件夹:
        File folder= File.createTempFile("junit", "");

如果上述语句仍然抛出相同的错误,您应该调查您的Windows用户权限,或者尝试在“完全权限”用户下运行测试。

0
在我的情况下似乎有所帮助的是明确地创建根文件夹;在你的情况下,将 folder.create() 放到你的代码中的某个位置。
很丑,我知道。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接