Java Reference
In-Depth Information
tests as much fun as writing the code that is being tested, but it helps enough that even those
who are test averse might be inclined to do the right thing.
JUnit works by marking your test code with the annotation @Test . It also allows you to define
a method that will be called before the tests are run, so that you can set up a test environment,
and after the tests are completed, allows you to clean up. In between, the tests that you define
in a class will be run.
Evaluation of the tests can be done in a couple of ways. The simplest is to end the test by
checking that the expected outcome was achieved, by using the JUnit class Assert . This class
gives you a large number of methods that can compare the result of your test run with the
value that you expect. If the assertion is true, the test is recorded as passing; if it is false, the
test is recorded as failing. The other mechanism that can be exploited is, again, an annotation.
Methods can be marked with the @Test expected annotation, which tests to see whether the
appropriate runtime exception is thrown by the method.
We have seen JUnit before, when I first talked about testing. If you recall, we wrote a test to
make sure that the implementation of the method that got the slugging percentage for a Bat-
ter object would give an answer that was consistent with the number of at-bats and the num-
ber of bases totaled for that Batter . To refresh your memory, the code looked like:
/**
* Test method for
* {@link org.oreilly.javaGoodParts.examples.impl.BatterImpl#getSlugging()}.
* This method will take the array of Batter objects stored in the private
* variable testBatters and made sure that all of them are consistent with
* regards to the slugging percentage, the number of at-bats, and the total
* number of bases recorded.
*/
@Test
public void testGetSlugging() {
for (int i = 0; i < testBatters.length; i++) {
try {
float testAvg = testBatters[i].getSlugging();
float calcAvg = (float)testBatters[i].getTotalBases()
/ (float) testBatters[i].getAtBats();
assertEquals("Slugging test", testAvg, calcAvg, .02); } catch
(NotEnoughAtBatsException e) {
assertEquals("Slugging exception", true,
(10 == (e.getNeeded() + testBatters[i].getAtBats())));
}
Search WWH ::




Custom Search