Java Reference
In-Depth Information
{2, 1, 1}, //expected, valueOne, valueTwo
{3, 2, 1}, //expected, valueOne, valueTwo
{4, 3, 1}, //expected, valueOne, valueTwo
});
}
E
public
ParameterizedTest(
double
expected,
double
valueOne,
double
valueTwo) {
this
.expected = expected;
this
.valueOne = valueOne;
this
.valueTwo = valueTwo;
}
F
@Test
public
void
sum() {
Calculator calc =
new
Calculator();
assertEquals(expected, calc.add(valueOne, valueTwo), 0);
}
}
G
H
To run a test class with the
Parameterized
test runner, you must meet the following
requirements. The test class must carry the
@RunWith
annotation with the
Parame-
terized
class as its argument
b
. You must declare instance variables used in the tests
C
and provide a method annotated with
@Parameters
D
, here called
getTest-
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. In our case, each array contains three elements because
the public constructor has three arguments. Our example uses this method to pro-
vide the input and expected output values for the tests. Because we want to test the
add
method of our
Calculator
program, we provide three parameters:
expected
value and two values that we add together. At
E
we specify the required constructor
for the test. Note that this time our test case doesn't have a no-argument constructor
but instead has a constructor that accepts parameters for the test. At
F
we finally
implement the
sum
@Test
method, which instantiates the
Calculator
program
G
,
and assert calls for the parameters we've provided
H
.
Running this test will loop exactly as many times as the size of the collection
returned by the
@Parameters
method. The execution of this single test case has the
same result as the execution of the following test cases with different parameters:
sum: assertEquals(2, calculator.add(1, 1), 0);
sum: assertEquals(3, calculator.add(2, 1), 0);
sum: assertEquals(4, calculator.add(3, 1), 0);
It's worth stepping through the
JU
nit runtime to understand this powerful feature:
JU
nit calls the static method
getTestParameters
D
. Next,
JU
nit loops for each
array in the
getTestParameters
collection
D
.
JU
nit then calls the only public con-
structor
E
. If there is more than one public constructor,
JU
nit throws an assertion
error.
JU
nit then calls the constructor
E
with an argument list built from the array