2

I am trying to test a method that copies a source file to a dest file using JUnit's TemporaryFolder. I get a Java IOException when I try run this test however. Does it matter where I make the declaration for the folder? (My test class has several different tests in it). And if so, what is the proper way to do it? I ask because I currently have several unit tests above this code, then I try to set up the testing for the file copying. Maybe the @Rule-@Before-@Test block needs to be in its own class? Here is the snippet where I have coded the test:

...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);
}

When I run this test class, all 11 of my tests now fail (which previously passed) and I get java.io.IOException: No such file or directory.

4

2 回答 2

2

所以查看JUnit Javadoc,我发现任何声明都@Rule必须是 public 的,而不是 static。所以我拿出了静电,只是有:

@Rule
public TemporaryFolder tmp = new TemporaryFolder();

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

于 2012-08-29T17:37:49.790 回答
1

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

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

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

于 2014-08-18T00:12:51.737 回答