JUnit4 の @Parameterized

テストケースを書くとき、一つのテストメソッド内で条件を変えながらループさせて assert したいことがありますが、assert に失敗した場合に残りのテストが実行されない点と、どこで失敗したのかわかりにくい点が困ります。TDD のアンチパターン (http://www.hyuki.com/yukiwiki/wiki.cgi?TddAntiPatterns) で言うところの “巨人” です。

JUnit4 なら Parameterized を使うと解決できます。

テストデータを返すメソッドに @Parameters を付けておきます。
@Parameters
public static Collection data() {
return Arrays.asList(new Object { { 0, 0 }, { 1, 1 }, { 2, 1 },
{ 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
}

コンストラクタでテストデータを受け取り、
public FibonacciTest(int input, int expected) {
fInput= input;
fExpected= expected;
}

テストで利用します。テストデータ分だけテストが実行されます。
@Test public void test() {
assertEquals(fExpected, Fibonacci.compute(fInput));
}

詳しくは API リファレンスをどうぞ。
http://www.junit.org/junit/javadoc/4.3/org/junit/runners/Parameterized.html