第74回 JUnit4 その2
引き続き「JUnit4」について学んでいきます。
前回はJUnit4の導入としてテストメソッドの書き方を学びました。
今回はテストメソッドの前処理と後処理について学びます。
複数のテストメソッドを実行するとき、共通の前処理を行いたい場合があります。
例えば、インスタンスの初期化であったり、DB接続などがそうです。
そのような場合、前処理を行うメソッドを作成し、@Beforeを付加します。
同様に、DB切断といった共通の後処理をするメソッドには@Afterを付加します。
また、複数のメソッドにこれらのアノテーションを付加した場合、全て実行されます。
では、実際に@Beforeと@Afterを付加したメソッドを作成してテストを実行してみましょう。
public class Sample { public Object returnNull() { return null; } public int returnOne() { return 1; } }
import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; 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()); } @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が返された"); } }
SampleTestクラスを実行すると、テスト結果が表示されます。
テストメソッド実行の際にそれぞれ前処理と後処理が行われているのが確認できますね。
なお、過去のJUnitでは、前処理にはsetupメソッド、後処理にはtearDownメソッドをオーバーライドして使います。
import junit.framework.Assert; import junit.framework.TestCase; import org.junit.runner.JUnitCore; public class SampleTest extends TestCase { private Sample sample = null; public static void main(String[] args) { JUnitCore.main(SampleTest.class.getName()); } protected void setUp() { System.out.println("テストメソッド前処理"); sample = new Sample(); } protected void tearDown() { System.out.println("テストメソッド後処理"); } public void testReturnNull() { Assert.assertNull("nullが返されなかった", sample.returnNull()); System.out.println("nullが返された"); } public void testReturnOne() { Assert.assertEquals("1が返されなかった", 1, sample.returnOne()); System.out.println("1が返された"); } }