【Java】JUnitのテストを継承を使って共通化する
Qiita →【Java】JUnitのテストを継承を使って共通化する - Qiita
テストケースの継承、やってみたらできたので……
これで、
- 前提条件を変えても同じテスト郡をパスする
- 実装は結構異なるけども同じテストをパスする
とかそういうのをコピペせずに書けます。
import static org.assertj.core.api.Assertions.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; @RunWith(Enclosed.class) public class TestSample { @Ignore public static class Template { @BeforeClass public static void _beforeClass() { // 共通の前処理 } @AfterClass public static void _afterClass() { // 共通の後処理 } @Before public void _setup() { // 共通の前処理 } @After public void tearDown() { // 共通の後処理 } @Test public void test1() { assertThat(1).isEqualTo(1); } @Test public void test2() { assertThat(1).isEqualTo(1); } } public static class TestA extends Template { @Before public void setup() { // 固有の前処理 } } public static class TestB extends Template { @Before public void setup() { // 固有の前処理 } @Test public void test3() { // 特別なテストケース } } }