Java Reference
In-Depth Information
* A class that checks an implementation of the Batter
* interface. An instance of the class will be initialized with
* an array of AtBatResult objects that will be used to generate
* statistics in a Batter instance. The tests will then ensure
* that the statistics reported are correct.
* For simplicity's sake, the current implementation
* only checks the Slugging Average.
*/
public class CheckBatter {
private Batter.AtBatResult[] testData;
public CheckBatter(Batter.AtBatResult[] data){
testData = data;
}
@Test
public void testGetSlugging() {
for (int i = 0; i < testBatters.length; i++) {
float testAvg = testBatters[i].getSlugging();
float calcAvg = (float)testBatters[i].getTotalBases()
/ (float)testBatters[i].getAtBats();
assertEquals("Slugging test", testAvg, calcAvg, .02);
}
...
}
This simple test uses the JUnit testing framework, which will be discussed in Chapter 11 .
The important thing to understand is that the test creates an object that holds an array of
AtBatResults instances. When passed an object that implements the Batter interface, it calls
the atBat() method with the results, and checks to make sure that the slugging average, total
bases, and total at-bats statistics obey the invariant that defines those statistics. This is a very
simple case; the real point to this example is that the test cases follow directly from the ex-
planation of the meaning of the methods in the interface, without needing to reference any of
the internal state of the object instance of the class being tested. That Java enables this sort of
abstract description and testing is one of the good parts of the language.
Now let's consider a second interface for our baseball statistics package, which we will use
to keep track of fielding statistics. Fielding has no relationship to hitting, so there is no need
to refer to any of the hitting statistics to explain the fielding statistics. Since we are using in-
terfaces as the unit of meaning, we will declare a new interface to deal with this new set of
statistics. Our fielding statistics interface looks like:
Search WWH ::




Custom Search