JUnit4.11から@Paremetersで名前を指定できるようになった

前までは



というような味気無い表示でどんなテストケースなのかよくわからなかった@Parameterアノテーションですが、JUnit4.11からにname属性を指定できるようになったようです。

https://github.com/junit-team/junit/wiki/Parameterized-tests#identify-individual-test-cases


{index}でパラメータの添字を{0}, {1}, …でパラメータのn番目の値を表示できます。

以下の例では

@Parameters(name = "No.{index}:Fibonacci.compute({0}) の結果は {1} のはず")

というようにしています。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

@RunWith(Parameterized.class)
public class FibonacciTest {

    /** 入力値 */
    private final int input;

    /** 期待値 */
    private final int expected;

    /**
     * コンストラクタ。
     *
     * @param input    入力値
     * @param expected 期待値
     */
    public FibonacciTest(int input, int expected) {
        this.input = input;
        this.expected = expected;
    }

    /**
     * テストデータ。
     * <pre>
     * [0]:入力値
     * [1]:期待値
     * </pre>
     *
     * @return テストデータ
     */
    @Parameters(name = "No.{index}:Fibonacci.compute({0}) の結果は {1} のはず")
    public static Iterable<Integer[]> testData() {
        return Arrays.asList(new Integer[][]{
                {0, 0},
                {1, 1},
                {2, 1},
                {3, 2},
                {4, 3},
                {5, 5},
                {6, 0}
        });
    }

    /** 実際に実行されるテストメソッド。 */
    @Test
    public void test() {
        assertThat(Fibonacci.compute(input),
                   is(expected));
    }

    /** テスト対象クラス */
    public static class Fibonacci {
        public static int compute(int n) {
            if (n == 0) return 0;
            if (n == 1) return 1;
            return compute(n - 1) + compute(n - 2);
        }
    }
}


これで、どんなテストなのかわかりやすくなりました。

ちなみに。。

Eclipseだと、name属性に丸括弧を使うと表示が途切れるバグがあるらしいです。
https://bugs.eclipse.org/bugs/show_bug.cgi?id=102512

上記のスクリーンショットIntelliJのものなので大丈夫でした:)