JUnit でテスト全体の実行前および実行後の処理を書く

例えば DB を実行する前や後に初期化する場合など BeforeClass や AfterClass よりももっと大きな単位で JUnit テストの前と後で実行したいことがある場合。

org.junit.runner.notification.RunListener を使う。

package my.hogehoge;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;

public class MyListener extends RunListener {
    @Override
    public void testRunStarted(Description description) throws Exception {
    }

    @Override
    public void testRunFinished(Result result) throws Exception {
    }
}

直接 JUnit を動かす場合は JUnitCore#addListener() などでこれを登録するといいらしい。 実際 JUnit 動かすのは maven-surefire-plugin 経由などで実行すると思うので、その場合は下記のように設定するとよい。 ちなみに 一つも Test アノテーションが付いたものがないと testRunStarted() なども呼ばれない。

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19</version>
                <configuration>
                    <properties>
                        <property>
                            <name>listener</name>
                            <value>my.hogehoge.MyListener</value>
                        </property>
                    </properties>
                </configuration>
            </plugin>
        <plugins>
    </build>