Java Reference
In-Depth Information
once before each test, so multiple times in a series of tests. Annotating computationally expensive
processes as @Before will slow your overall testing down. The tear‐down methods actually func-
tion similarly to the finally block of a try‐catch‐finally statement. If you allocate resources using a
@Before method, you will need to release them using an @After method. If you allocate resources
using a @BeforeClass method, you need to release them using an @AfterClass method. Just as the @
BeforeClass runs once before everything else starts, @AfterClass runs exactly once after everything
else finishes. Similarly, @After methods will run after each test. These @After and @AfterClass
methods will run even if there is an exception thrown, just like the finally block.
Assertions are the main component you will use in your JUnit tests. There are several assert meth-
ods that allow you to state what you expect and the tests will check if it's correct. Any incorrect
assert statement will result in a test failure. Here is a list of some assert methods you might find
useful in your tests:
assertEquals(a, b) : Expect a and b to be equal.
assertArrayEquals(arrayA, arrayB) : Expect all elements in A and B to be equal.
assertTrue(a) : Expect a to be true.
assertFalse(b) : Expect b to be false.
assertNull(a) : Expect a to be null.
assertNotNull(b) : Expect b to not be null.
assertSame(a,b) : Expect a and b to reference the same object.
assertNotSame(a,b) : Expect a and b not to reference the same object.
note The assertEquals() method is slightly different for different data
types. As you have seen previously, some number types like doubles are
not precise due to rounding. To accommodate these shortcomings, the
assertEquals() method for doubles or floats has an additional parameter,
called epsilon , which allows you to choose how different two doubles can be
and still be considered equal values. The format is then: assertEquals(double
a, double b, double epsilon) or assertEquals(1.51, 1.52, 0.01) , for
example.
With these concepts, you're ready to start testing. You can start by declaring some objects that you
will use for the tests. A static Scanner object is used just to symbolize the resources that you might
need for your tests; it is initialized in the setUpBeforeClass() method and closed in the tearDown-
AfterClass() method. Some integers, an array, and an object are also added to compare values
using the assert methods. The int s are initialized in the setup() method. Then using these (and
the other variables created in the test methods), each of the assert methods is demonstrated. The
entire test class looks like this:
import static org.junit.Assert.*;
import java.util.Scanner;
Search WWH ::




Custom Search