[Junit] Including the parameters in the names of parameterized tests

Junit 4.11 has added the ability to include the name of the parameters in a Parameterized test. This is done by providing a String to the name argument of the @Parameters annotation. Here is an example of a test that uses this feature:

@RunWith(Parameterized.class)
public class AdditionTest 
{
    @Parameters(name="{0} + {1}")
    public static Collection<Object[]> parameters() {
        Object[][] data = new Object[][] {{1, 2, 3}, {0, 3, 3}, {-1, 1, 0}};
        return Arrays.asList(data);
    }
    
    private final int first;
    
    private final int second;
    
    private final int expected;
    
    public AdditionTest(int first, int second, int expected) {
        this.first = first;
        this.second = second;
        this.expected = expected;
    }
    
    @Test
    public void testAddition() {
        Assert.assertThat(first + second, CoreMatchers.is(expected));
    }
}

The arguments are substitued into the numeric arguments of message. In the above example, the tests would be named “testAddition[1 + 2]“, “testAddition[0 + 3]” and “testAddition[-1 + 1]“. Using this feature, you would be able to tell what the parameters were without having to refer back to your unit test code.

Prior to 4.11 the tests would have been named “testAddition[0]“, “testAddition[1]” and “testAddition[2]“, where the 0, 1 and 2 correspond to the index in the Collection that was provided as the parameters – you have to refer back to your unit test code to figure out what the parameters were. If you do NOT specify the name in 4.11, the tests will also be named in this fasion.

Advertisements