Wednesday, April 20, 2016

Parameterized JUnit Tests

JUnitParams provides a runner - JUnitParamsRunner, to add parameterized tests in a test class. With this runner parameterized and non-parameterized test methods can be combined in the same class.

@RunWith(JUnitParamsRunner.class)
public class ParameterizedTests {
    @Parameters({"1, true", "2, false"})
    @Test
    public void test1(int num, boolean result) {
        assertThat(num == 1, is(result));
    }
}
To pass in objects or null values, a separate method can be setup, which then can be added to the @Parameters annotation.
@RunWith(JUnitParamsRunner.class)
public class ParameterizedTests {
    private Object[] params() {
        return $(
                $(1, true),
                $(2, false)
        );
    }

    @Parameters(method = "params")
    @Test
    public void test1(int num, boolean result) {
        assertThat(num == 1, is(result));
    }
}

No comments: