LoginSignup
10
6

More than 5 years have passed since last update.

【Java】JUnitのテストを継承を使って共通化する

Posted at

テストケースの継承、やってみたらできました。

これで、
* 前提条件を変えても同じテスト郡をパスする
* 実装は結構異なるけども同じテストをパスする
とかそういうのをコピペせずに書けます。

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() {
            // 特別なテストケース
        }
    }
}
10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6