All Contents are referenced from Junit In Action 2nd Edtion
The Parameterized test runner allows you to run a test many times with different sets of parameters.
the code need testing
public class Calculation {
public static int add(int a, int b){
return a + b;
}
}
test case with Parameterized test
// The test class must carry the @RunWith annotation
// with the Parameterized class as its argument
// The JUnit class Parameterized is one of JUnit’s many test runners.
// A test runner allows you to tell JUnit how a test should be run
@RunWith(value=Parameterized.class)
public class SimpleTestCase {
// declare instance variables used in the test
// i.e. input values for calculation and expected value
private int operatorA;
private int operatorB;
private int expectedSum;
//a constructor that accepts parameters for the test
public SimpleTestCase(int operatorA, int operatorB, int expectedSum) {
this.operatorA = operatorA;
this.operatorB = operatorB;
this.expectedSum = expectedSum;
}
// provide a method annotated with @Parameters
// The method provides parameters
// to be injected into the test class constructor by Parameterized Class.
// The signature of method has to be public static java.util.Collection,
// without parameters.
@Parameters
public static Collection<Integer[]> getParameters(){
return Arrays.asList(new Integer[][]{ {1,2,3},
{2,3,5},
{3,4,7},
{4,5,9} });
}
// the test method
// Running this test will loop exactly as many times as the size of the collection
// returned by the @Parameters method
@Test
public void test() {
assertEquals(expectedSum, Calculation.add(operatorA, operatorB));
}
}
one test case runs exactly as many times as the size of the collection provided by @Parameters method.
each test runs with a set of parameters within the collection.