第75回 JUnit4 その3
引き続き「JUnit4」について学んでいきます。
前回はテストメソッドの前処理と後処理について学びました。
今回はテストクラスの前処理と後処理について学びます。
テストクラスの前処理を行うメソッドには、@BeforeClassを付加します。
@Beforeを付加したメソッドがテストメソッドごとに実行されるのに対して、
@BeforeClassを付加したメソッドはテストクラスの実行前に一度だけ実行されます。
同様にテストクラスの実行後に一度だけ実行するメソッドには@AfterClassを付加します。
これらはJUnit4の新機能で、過去のJUnitには同等の機能はありません。
@BeforeClassや@AfterClassを付加するメソッドがpublicかつstaticでない場合、
コンパイルエラーにはなりませんが、実行時例外が発生します。
では、実際に@BeforeClassと@AfterClassを使ってテストを実行してみましょう。
public class Sample {
public Object returnNull() {
return null;
}
public int returnOne() {
return 1;
}
public boolean returnTrue() {
return true;
}
}
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
public class SampleTest {
private Sample sample = null;
public static void main(String[] args) {
JUnitCore.main(SampleTest.class.getName());
}
@BeforeClass
public static void beforeTestClass() {
System.out.println("テストクラス前処理");
}
@AfterClass
public static void afterTestClass() {
System.out.println("テストクラス後処理");
}
@Before
public void beforeTestMethod() {
System.out.println("テストメソッド前処理");
sample = new Sample();
}
@After
public void afterTestMethod() {
System.out.println("テストメソッド後処理");
}
@Test
public void returnNull() {
assertNull("nullが返されなかった", sample.returnNull());
System.out.println("nullが返された");
}
@Test
public void returnOne() {
assertEquals("1が返されなかった", 1, sample.returnOne());
System.out.println("1が返された");
}
@Test
public void returnTrue() {
assertTrue("trueが返されなかった", sample.returnTrue());
System.out.println("trueが返された");
}
}
SampleTestクラスを実行すると、テスト結果が表示されます。
テストクラス実行の際に一度だけ前処理と後処理が行われているのが確認できますね。

