Java Reference
In-Depth Information
Listing 1.4
The JUnit CalculatorTest program
import static org.junit.Assert.*;
import org.junit.Test;
B
C
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calculator = new Calculator();
double result = calculator.add(10, 50);
assertEquals(60, result, 0);
}
}
This is a much simpler test; let's walk through it. At B , we start by defining a test class.
The only restriction is that the class must be public; we can name it whatever we like.
It's common practice to end the class name with Test . Notice also that in contrast to
JU nit 3 where we needed to extend the TestCase class, this requirement has been
removed in JU nit 4.
At C , we mark the method as a unit test method by adding the @Test annotation. 6
A best practice is to name test methods following the test XXX pattern. JU nit doesn't
have method name restrictions. You can name your methods as you like; as long as
they have the @Test annotation, JU nit will execute them.
At D , we start the test by creating an instance of the Calculator class (the “object
under test”), and at E , as before, we execute the test by calling the method to test,
passing it two known values.
At F , the JU nit framework begins to shine! To check the result of the test, we call
an assertEquals method, which we imported with a static import on the first line of
the class. The Javadoc for the assertEquals method is as follows:
D
E
F
/**
* Asserts that two doubles or floats are equal to within a positive delta.
* If the expected value is infinity then the delta value is ignored.
*/
static public void assertEquals(
double expected, double actual, double delta)
In listing 1.4, we passed assertEquals these parameters:
expected = 60
actual = result
delta = 0
Because we passed the calculator the values 10 and 50, we tell assertEquals to expect
the sum to be 60. (We pass 0 as the delta because we're adding integers.) When we
called the calculator object, we tucked the return value into a local double named
result . Therefore, we pass that variable to assertEquals to compare against the
expected value of 60.
6
Annotations were first introduced in JDK 1.5, so in order to use them you need to have version 1.5 or later of the JDK .
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search