Parameterized test

Occasionally developers want the ability to provide a dynamic data set to a unit test. You could accomplish this by connecting to a database but that would fall under an integration test. Junit 4 introduced a new feature called Parameterized which allows you to declare a static data set that will get passed to a test. Follow the steps below to create Parameterized tests.

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

private int a;
private int b;
private int expected;

Create constructor

public ParamertizedTest(int a, int b, int expected) {
    this.a = a;
    this.b = b;
    this.expected = 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