Dynamic number of tests – JUnit4

In our project I have several JUnit tests that e.g. take every file from a directory and run a test on it. If I implement a testEveryFileInDirectory method in the TestCase this shows up as only one test that may fail or succeed. But I am interested in the results on each individual file. How can I write a TestCase / TestSuite such that each file shows up as a separate test e.g. in the graphical testrunner of eclipse? (Coding an explicit test method for each file is not an option.)

package com.vel.qa.tests.detailedtests;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

public class ParameterizedTest {

	public void method() {
		System.out.println("Set Up method  ");

	@Parameters(name = "{0}")
	public static Collection<Object[]> data() {
		// load the files as you want from the directory
		Collection<Object[]> data = new ArrayList<Object[]>();
		for (int i = 0; i < 10; i++) {
			File file = new File("file_name_" + i);
			Object[] fileArg1 = new Object[] { file };
		return data;

	private File fInput;

	// Constructor with arguments
	public ParameterizedTest(File input) {
		this.fInput = input;

	// This test will be called multiple times depends on size of the parameters
	// set at the @paramenters method.
	public void test() {
		System.out.println("test called  ");
		// do more validation based on your requirements.

	public void tearDown() {

  • 1. Junit will call this static method (@Parameters) first to get all the collection of data
  • 2. For Each array in the collection , Junit will create an object of this class by calling the constructor(argument) you provided and then call set up method(@Before) and then call the test method (@Test) that you have written.
  • 3. In that way if size of the collection is 50, then 50 times test method (@Test)will be called by JUnit.
  • The results of the above program looks like as shown below.




    One thought on “Dynamic number of tests – JUnit4

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )


    Connecting to %s