Quantcast
Channel: Planet Apache
Viewing all articles
Browse latest Browse all 9364

Gary Gregory: JUnit 4.9 to the rescue with @ClassRule

$
0
0

In a previous article titled “JUnit @Rule not initialized before @BeforeClass“, I bemoaned the fact that an @Rule could not be set up to run before an @BeforeClass.

It appears my wish has been answered with the release of JUnit 4.9 and the new @ClassRule annotation.

The only change required to make our example work is to replace @Rule with @ClassRule:

package test;

import java.io.File;
import java.io.IOException;

import junit.framework.Assert;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class TemporaryFolderRuleBeforeClass {
    @ClassRule
    public static TemporaryFolder testFolder = new TemporaryFolder();

    @BeforeClass
    public static void testInTempFolder() throws IOException {
        File tempFile = testFolder.newFile("file.txt");
        File tempFolder = testFolder.newFolder("folder");
        System.out.println("Test folder: " + testFolder.getRoot());
        // test
        Assert.assertNotNull(testFolder.getRoot());
    }

    @Test
    public void test() {
        // ...
    }
}

Voila! It just works, the @ClassRule is set up correctly before the @BeforeClass method is called. Thank you JUnit 4.9!



Viewing all articles
Browse latest Browse all 9364

Trending Articles