About
When running a parameterized test class, test object instances are created for the cross-product of:
- the test methods
- and the test data elements.
Then for instance, for 2 test methods with two data elements, will become 4 instances.
Articles Related
Code
package com.gerardnico.junit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
/**
* Created by gerard on 29-05-2016.
*/
@RunWith(value = Parameterized.class)
public class ParametersTest {
// This function will call the constructor for each element of its array
//
// The set of test (and/of parameters) are then declared below
// The name argument below will be present in the Junit output
@Parameterized.Parameters(name = "{index}: add({0}-{1})={2}")
public static Iterable<Object[]> data1() {
return Arrays.asList(new Object[][]{
{1, 1, 0},
{2, 2, 0},
{8, 2, 6},
{4, 5, -1}
});
}
// The constructor get called for each row of the array defined above
// where the Parameters are the value of each element in a row
public ParametersTest(int numberA, int numberB, int expected) {
this.numberA = numberA;
this.numberB = numberB;
this.expected = expected;
}
// Variable that will hold the value
// for each test (ie for each row)
private int numberA;
private int numberB;
private int expected;
@Test
public void test_substraction() {
assertEquals(expected, numberA - numberB);
}
}
Output:
[0: add(1-1)=0]
test_substraction[0: add(1-1)=0]
[1: add(2-2)=0]
test_substraction[1: add(2-2)=0]
[2: add(8-2)=6]
test_substraction[2: add(8-2)=6]
[3: add(4-5)=-1]
test_substraction[3: add(4-5)=-1]