Simplify parameterizations with JUnitParams

  junit

Order

The usage of junit4′ s Parameterized tests is too laborious. Here’s how to use JUnit Parameters to simplify Parameterized tests.

Junit4 native Parameterized tests instance

@RunWith(Parameterized.class)
public class FibonacciTest {
    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {     
                 { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }  
           });
    }

    private int fInput;

    private int fExpected;

    public FibonacciTest(int input, int expected) {
        fInput= input;
        fExpected= expected;
    }

    @Test
    public void test() {
        assertEquals(fExpected, Fibonacci.compute(fInput));
    }
}

Use of JUnitParams

maven

<dependency>
  <groupId>pl.pragmatists</groupId>
  <artifactId>JUnitParams</artifactId>
  <version>1.1.0</version>
  <scope>test</scope>
</dependency>

Example

@RunWith(JUnitParamsRunner.class)
public class PersonTest {

  @Test
  @Parameters({"17, false", 
               "22, true" })
  public void personIsAdult(int age, boolean valid) throws Exception {
    assertThat(new Person(age).isAdult(), is(valid));
  }
  
}

Junit5 update

Of course junit5 also simplifies the use of Parameterized tests, as follows:

@ParameterizedTest
@EnumSource(value = TimeUnit.class, names = { "DAYS", "HOURS" })
void testWithEnumSourceInclude(TimeUnit timeUnit) {
    assertTrue(EnumSet.of(TimeUnit.DAYS, TimeUnit.HOURS).contains(timeUnit));
}

Summary

If you are still using a version prior to junit5, you can try to use JUnitParams to simplify parameters. If you have already used junit5, congratulations, you can easily carry out Parameterized tests without introducing additional JUnitParams.

doc