【问题标题】:JUnit : When do I declare a TemporaryFolder object?JUnit:我什么时候声明一个 TemporaryFolder 对象?
【发布时间】:2012-08-29 16:56:25
【问题描述】:

我正在尝试测试一种使用 JUnit 的 TemporaryFolder 将源文件复制到目标文件的方法。但是,当我尝试运行此测试时,我得到了 Java IOException。我在哪里声明文件夹有关系吗? (我的测试类中有几个不同的测试)。如果是这样,正确的方法是什么?我问是因为我目前在此代码上方有几个单元测试,然后我尝试为文件复制设置测试。也许@Rule-@Before-@Test 块需要在自己的类中?这是我编写测试代码的 sn-p:

...other tests...then:

@Rule
public static TemporaryFolder tmp = new TemporaryFolder();
private File f1, f2;

@Before
public void createTestData() throws IOException {
    f1 = tmp.newFile("src.txt");
    f2 = tmp.newFile("dest.txt");

    BufferedWriter out = new BufferedWriter(new FileWriter(f1));
    out.write("This should generate some \n" +
            "test data that will be used in \n" +
            "the following method.");
    out.close();
}

@Test
public void copyFileTest() {

    out.println("file 1 length: " + f1.length());
    try {
        copyFile(f1, f2);
    } catch (IOException e) {
        e.getMessage();
        e.printStackTrace();
    }

    if (f1.length() != f2.length())
        fail();
    else if (!f1.equals(f2))
        fail();
    assertSame(f1, f2);
}

当我运行这个测试类时,我的所有 11 个测试现在都失败了(之前通过了),我得到了java.io.IOException: No such file or directory

【问题讨论】:

    标签: java unit-testing testing junit temporary-directory


    【解决方案1】:

    所以查看JUnit Javadoc,我发现@Rule 下的任何声明都必须是公开的,并且不是静态的。所以我拿出了静态的,只是有:

    @Rule
    public TemporaryFolder tmp = new TemporaryFolder();
    

    我仍然不确定当您的班级中有其他不使用@Rule 声明的单元测试时,在哪里进行此声明是否重要,但这确实让我能够成功地运行我的测试。

    【讨论】:

      【解决方案2】:

      如果你真的想将 TemporaryFolder 声明为静态的,你可以使用 @ClassRule 来注释包含 Rule 的静态字段。

      @ClassRule
      public static TemporaryFolder tmp = new TemporaryFolder();
      

      参考:http://junit-team.github.io/junit/javadoc/4.10/org/junit/ClassRule.html

      【讨论】:

        猜你喜欢
        • 2012-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-11
        • 1970-01-01
        • 1970-01-01
        • 2016-10-06
        相关资源
        最近更新 更多