Java Reference
In-Depth Information
in the way things are done. Remember that you can include the
@BeforeClass
and
@AfterClass
annotated methods in the suite. This wasn't possible with the 3.x versions
of
JU
nit.
A.4.3
Parameterized tests
As you saw, the
@RunWith
annotation lets you define a test runner to use. The
Suite
test runner that we already presented lets you run your test cases in a suite.
Another test runner that's bundled with the
JU
nit distribution is the
Parameterized
test runner. This test runner lets you run the same tests with different input test
data. We know that an example is worth several pages of explanation, so listing A.10
shows the example.
Listing A.10
Parameterized test runner in action
@RunWith(value=Parameterized.
class
)
public
class
SquareRootTest {
B
private
int
expected;
private
int
actual;
C
@Parameters
public
static
Collection data() {
return
Arrays.asList(
new
Object[][] {
{ 1, 1 },
{ 2, 4 },
{ 3, 9 },
{ 4, 16 },
{ 5, 25 },
});
}
D
public
SquareRootTest(
int
expected,
int
actual) {
this.
expected = expected;
this
.actual = actual;
}
E
@Test
public
void
squareRoot() {
Calculator calculator =
new
Calculator();
assertEquals(expected, calculator.squareRoot(actual));
}
}
Imagine that we have a
squareRoot
method in our
Calculator
class that we want to
test. This listing demonstrates how to test this method with different input test data. We
start by declaring the use of the
Parameterized
test runner at
B
. Then, at
C
, we
define the static
data()
method that we annotate with
@Parameters
, denoting that this
method returns the actual test data for our test. This test data is made from a
java.util.List
, and each element of the
List
is a two-dimensional array, the ele-
ments of which will be used to make a new instance of the
SquareRootTest
. At
D
we fill
in the test data and return it. At
E
we start the test method, and inside it we instantiate
F