Running Parameterized JUnit Tests

The Parameterized test runner allows you to run a test many times with different sets of parameters. To run a test class with the Parameterized test runner, you must meet the following requirements.

  1. The test class must carry the @RunWith annotation with the Parameterized class as its argument.
  2. The test class must declare instance variables used in the tests.
  3. Provide a method annotated with @Parameters. The signature of this method must be @Parameters public static java.util.Collection, without parameters. The Collection elements must be arrays of identical length. This array length must match the number of arguments of the only public constructor.
  4. The test class must have a constructor matching the elements in the array.
package com.memorynotfound.test;

import com.memorynotfound.Math;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)      // => #1
public class ParametrizedTest {

    private final int input;       // => #2
    private final int expected;

    public ParametrizedTest(int input, int expected) {      // => #4
        this.input = input;
        this.expected = expected;
    }

    @Parameters                    // => #3
    public static Collection data(){
        return Arrays.asList(new Integer[][] {
                {0,1},{1,1},{2,2},{3,6},{4,24},{5,120}});
    }

    @Test
    public void calculatorAddTest(){
        System.out.println("factorial of: " + input + " should be: " + expected);
        assertEquals(expected, Math.fact(input));
    }
}
package com.memorynotfound;

public class Math {

    public static int fact(int n) {
        int result;
        if (n==0 || n==1)
            return 1;

        result = fact(n-1) * n;
        return result;
    }
}

Generated output

factorial of: 0 should be: 1
factorial of: 1 should be: 1
factorial of: 2 should be: 2
factorial of: 3 should be: 6
factorial of: 4 should be: 24
factorial of: 5 should be: 120

You may also like...