2

JUnitのを使用してソースファイルをdestファイルにコピーするメソッドをテストしようとしていますTemporaryFolderIOExceptionただし、このテストを実行しようとするとJavaが表示されます。フォルダの宣言をどこで行うかは重要ですか?(私のテストクラスには、いくつかの異なるテストがあります)。もしそうなら、それを行うための適切な方法は何ですか?現在、このコードの上にいくつかの単体テストがあるので、ファイルコピーのテストを設定しようとしています。たぶん---ブロックはそれ自身@Ruleのクラスにある必要がありますか?これが私がテストをコーディングしたスニペットです:@Before@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);
}

このテストクラスを実行すると、11個のテストすべてが失敗し(以前は合格)、が取得されjava.io.IOException: No such file or directoryます。

4

2 に答える 2

2

したがって、JUnit Javadocを見ると、での宣言は静的ではなく@Ruleパブリックである必要があることがわかりました。だから私は静的なものを取り出して、ただ持っています:

@Rule
public TemporaryFolder tmp = new TemporaryFolder();

クラス内に宣言を使用しない他の単体テストがある場合に、この宣言がどこで行われるかが重要かどうかはまだわかりませんが@Rule、これにより、テストを正常に実行できました。

于 2012-08-29T17:37:49.790 に答える
1

本当にTemporaryFolderを静的として宣言したい場合は、Ruleを含む静的フィールドに注釈を付けるために使用される@ClassRuleを使用できます。

@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 に答える