JUnit test with dynamic number of tests

Take a look at Parameterized Tests in JUnit 4.

Actually I did this a few days ago. I’ll try to explain …

First build your test class normally, as you where just testing with one input file.
Decorate your class with:


Build one constructor that takes the input that will change in every test call (in this case it may be the file itself)

Then, build a static method that will return a Collection of arrays. Each array in the collection will contain the input arguments for your class constructor e.g. the file. Decorate this method with:


Here’s a sample class.

public class ParameterizedTest {

    private File file;

    public ParameterizedTest(File file) {
        this.file = file;

    public void test1() throws Exception {  }

    public void test2() throws Exception {  }

    public static Collection<Object[]> data() {
        // load the files as you want
        Object[] fileArg1 = new Object[] { new File("path1") };
        Object[] fileArg2 = new Object[] { new File("path2") };

        Collection<Object[]> data = new ArrayList<Object[]>();
        return data;

Also check this example

Leave a Comment