Parameterization of Unit Tests

Parameterization is a feature introduced in JUnit 4 whereby the same test can be invoked multiple times by changing the test input data. With this feature the test cases can be abstracted to a single test case which can be run against varying test data.

When the Parameterized Test Runner is invoked the ‘data-generating’ method will be triggered and it will return a Collection of Arrays where each Array is a set of test data. The test runner will then instantiate the test class and pass the first test data to the constructor. Each test is then executed with this test data and once all the test have been executed, the test runner shall re-instantiate the test class with second set of test data and so on.

With parameterization in place, the developer is only required to list the input and expected output. The developer need not craft a relationship between inputs and outputs into a Theory.

Guidelines for writing Parameterized JUnit:

  1. Mark the test class with annotation @RunWith. This will mark the test class to be run with the runner you specified in this annotation instead of the default JUnit runner. Consider sample code below:
@RunWith(Parameterized.class)

public class UnitTest {..}

2. The method marked with @Parameterized has to be static and should return a collection. The items added to this collection has to be passed to the Unit Test Constructor as an argument. Please look at the following example:

@RunWith(Parameterized.class)
public class UnitTest {
// JUnit Constructor
public UnitTest(TestInput testInput) { ... }
    
@Parameters

public static Collection<TestInput[]> inputParams() {
return ...;
}
}