技術開発日記

技術やら日々思ったことを綴ってます。

Junitの構造化

JUnitでRunWithアノテーションにEnclosed.classを追加するとテストクラスを構造化できると知って、早速試して見たら、確かにこれは便利だ。
何のテストをしているかをクラスごとに区別できるので、テストケースを後から追加したい時や実施の結果をわかりやすくしたいといったときには重宝しそう。
初期化処理(@Beforeや@Afterなど)も各クラスで指定できるのもGood。

以下は簡単なサンプルです。

@RunWith(Enclosed.class)
public class ArraryTest {

    /**
     * 配列のサイズのテスト
     */
    public static class ArraySizeTest {
        private ArrayList<String> target;

        @Before
        public void setUp() throws Exception {
            target = new ArrayList<String>();
        }

        @Test
        public void testSize() {
            assertThat(target.size(), is(0));
        }

    }

    /**
     * 配列の中身のテスト
     */
    public static class ArrayContentTest {
        private ArrayList<String> target;

        @Before
        public void setUp() throws Exception {
            target = new ArrayList<String>();
            target.add("Sample");
        }

        @Test
        public void testContent() {
            assertThat(target.get(0), is("Sample"));
        }

    }
}