Parameterized test with field injection

An alternative to creating a construtor based parameter test is to declare parameters with the @Parameter annotation. When doing so, the data declared will be injected directly into the fields with out need a constructor. Follow the outline below to set up your unit test.

Setup

Simple calculator class

static class Calculator {

    public static int add(int a, int b) {
        return a + b;
    }
}

Create a collection

@Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {
            {0, 0, 0},
            {1, 0, 1},
            {0, 1, 1},
            {1, 1, 2},
            {1, 2, 3},
            {2, 1, 3}
        });
}

Declare parameters

The value represents the index of the array specified above. For the first iteration above, the value for int a would be 0 or the 0 based index.

@Parameter (value = 0) public int a;
@Parameter (value = 1) public int b;
@Parameter (value = 2) public int expected;

Parameterized test

@Test
public void test_calculator_add () {

    logger.info("a=" + a + " b " + b + " = c " + expected);

    int calculatedValue = Calculator.add(a,  b);
    assertEquals(expected, calculatedValue);
}

Output

a=0 b 0 = c 0
a=1 b 0 = c 1
a=0 b 1 = c 1
a=1 b 1 = c 2
a=1 b 2 = c 3
a=2 b 1 = c 3