javajunitjunit4parameterized

Changing names of parameterized tests


Is there a way to set my own custom test case names when using parameterized tests in JUnit4?

I'd like to change the default — [Test class].runTest[n] — to something meaningful.


Solution

  • 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:

    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).