JUnit 4.9 to the rescue with @ClassRule

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 {
    public static TemporaryFolder testFolder = new TemporaryFolder();

    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

    public void test() {
        // ...

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


One thought on “JUnit 4.9 to the rescue with @ClassRule

  1. Antonio

    Hey there! I’ve been following your web site for a long time now and finally got the courage to go ahead and give you a shout out from Humble Tx! Just wanted to say keep up the great work!



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s