Java Reference
In-Depth Information
Then, in the next chapter, we use an example application to show you how to use
these core
JU
nit concepts. We demonstrate best practices for writing and organizing
test code.
2.1
Exploring core JUnit
The
CalculatorTest
program from chapter 1, shown in listing 2.1, defines a test class
with a single test method
testAdd
.
The requirements to define a test class are that the class must be public and con-
tain a zero-argument constructor. In our example, because we don't define any other
constructors, we don't need to define the zero-argument constructor; Java creates it
for us implicitly.
The requirements to create a test method are that it must be annotated with
@Test
, be public, take no arguments, and return
void
.
Listing 2.1
The
CalculatorTest
test case
import
static
org.junit.Assert.assertEquals;
import
org.junit.Test;
public
class
CalculatorTest {
@Test
public
void
testAdd() {
Calculator calculator =
new
Calculator();
double
result = calculator.add(1, 1);
assertEquals(2, result, 0);
}
}
JU
nit creates a new instance of the test class before invoking each
@Test
method. This
helps provide independence between test methods and avoids unintentional side
effects in the test code. Because each test method runs on a new test class instance, we
can't reuse instance variable values across test methods.
To perform test validation, we use the
assert
methods provided by the
JU
nit
Assert
class. As you can see from the previous example, we statically import these
methods in our test class. Alternatively, we can import the
JU
nit
Assert
class itself,
depending on our taste for static imports. Table 2.1 lists some of the most popular
assert
methods.
Assert
methods with two value parameters follow a pattern worth memorizing: the
first parameter (
A
in the table) is the expected value, and the second parameter (
B
in
the table) is the actual value.
JU
nit provides many other methods, such as
assertArrayNotEquals
,
assertNot-
Same
,
assertNotTrue
, and so on. It also provides the same methods with a different
signature—without the
message
parameter. It's a best practice to provide an error
message for all your
assert
method calls. Recall Murphy's Law and apply it here;
when an assertion fails, describe what went wrong in a human-readable message.