Skip to main content
blog title image

2 minute read - Java For Testers Java JUnit JUnit Examples

JUnit 4 Parameterized Tests

Jun 27, 2020

JUnit 4 supports parameterizing a Test class to run the test methods in the class with multiple data values.

Explanation Video

Test Classes Need to be Annotated with Parameterized.class

@RunWith(Parameterized.class)
public class ParameterizedJunit4ExampleTest {

Create a static method to supply the data

    @Parameterized.Parameters
     public static Collection<Object[]> versionCombos() {

        List<Object[]> args = new ArrayList<>();

        // code to generate data here

        return args;
    }
  • this method can read from files etc,
  • so long as it returns a Collection of Object arrays

e.g. this method creates a list of object arrays to create a combination of data i.e. [(1,11), (1,12),…,(2,11) etc.]

    @Parameterized.Parameters
     public static Collection<Object[]> versionCombos() {

        List<Object[]> args = new ArrayList<>();

        for(int getversion=1; getversion<= 5; getversion++){
            for(int version=11; version<= 15; version++){
                args.add(new Object[]{getversion, version});
            }
        }
        return args;
    }

The Parameters method can have a name attribute

When tests are run they are shown as [0], [1] etc.

But it is possible to give them a dynamic name based on the data using a name attribute

@Parameterized.Parameters(
         name = "using combo getversion {0} and check version {1}")
     public static Collection<Object[]> versionCombos() {

This would display names as:

  • using combo getversion 1 and check version 11
  • using combo getversion 1 and check version 12
  • using combo getversion 1 and check version 13

Because the {0}, {1} are replaced with the data from the Object []

The Test Class needs a constructor

    public ParameterizedJunit4ExampleTest(
                int getversion, int checkversion){
        this.getversion = getversion;
        this.checkversion=checkversion;
    }
  • The arguments to the constructor should match the values in the Object[] entries.
  • A new class will be instantiated for all the Object[] entries in the collection
  • The test methods in the class will be run for each instantiation

Supporting Source Code

Official documentation:

You can find the supporting source code for this over at:

And specifically: