Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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

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() {
            // 特別なテストケース
        }
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away