Changing names of parameterized tests

This feature has made it into JUnit 4.11.

To use change the name of parameterized tests, you say:

@Parameters(name="namestring")

namestring is a string, which can have the following special placeholders:

  • {index} – the index of this set of arguments. The default namestring is {index}.
  • {0} – the first parameter value from this invocation of the test.
  • {1} – the second parameter value
  • and so on

The final name of the test will be the name of the test method, followed by the namestring in brackets, as shown below.

For example (adapted from the unit test for the Parameterized annotation):

@RunWith(Parameterized.class)
static public class FibonacciTest {

    @Parameters( name = "{index}: fib({0})={1}" )
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
                { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
    }

    private final int fInput;
    private final int fExpected;

    public FibonacciTest(int input, int expected) {
        fInput= input;
        fExpected= expected;
    }

    @Test
    public void testFib() {
        assertEquals(fExpected, fib(fInput));
    }

    private int fib(int x) {
        // TODO: actually calculate Fibonacci numbers
        return 0;
    }
}

will give names like testFib[1: fib(1)=1] and testFib[4: fib(4)=3]. (The testFib part of the name is the method name of the @Test).

Leave a Comment