# Learn Object-Oriented Java the Hard Way

## Exercise 10: Automated Testing with Arrays

Two exercises ago, `SphereCalcTester` did a decent job testing our object, but it took a lot of code for each test, and there was a lot of repeated code. It is important to make testing code as easy as possible to write and to automatically run. Otherwise, you might be tempted to not test your code, and that doesn’t lead anywhere good.

So here is an example of a tester for `SphereCalc4` that makes it much easier to add additional tests without adding any extra code!

This code uses arrays of doubles to hold the expected inputs and outputs, and they are in the same order in each array so that `areas[0]` holds the expected area output for radius `inputs[0]` and `volumes[0]` holds the corresponding expected volume. Arrays used like this are called “parallel” arrays.

This isn’t the absolute best way to do this, but it’s good enough for now. We’ll see an even better testing technique later in the book.

### What You Should See

Lines 4 through 24 just contain the values for inputs and outputs. I like to list them one per line like this, but Java doesn’t care if you put them all on one line. If you do put them all on one line, it’d probably be good for your sanity if you add extra spaces so that the corresponding entries line up, like so:

On line 28 we just create a single `SphereCalc4` object, which will be reused each time. Then there’s a loop through each value in the arrays. NOTE: If you accidentally make the arrays different lengths, then this code might blow up. That’s one of the problems with parallel arrays.

On lines 30 through 36 we pull out the expected radius, area and volume and put them into nicely-named but easy-to-type variables, and then tell the object to use that radius and get the computed area and volume from our object. So a is the expected area, and A is the actual area according to our object.

Then we can just use the same `isNear()` function from earlier together with `if` statements to see if what we got matches what was expected. We increment a variable for each “PASS” but don’t bother printing anything. If there’s a failure, we print an error message.

Once the loop is over, there should be twice as many “passes” as inputs, so we check that and print a summary message if everything is good.

Not too bad, huh? Adding more tests is as easy as just adding more numbers to the arrays, but none of the other code has to change. And it’s easy to tell when everything turned out as expected and easy to see specifically what went wrong when something isn’t right.

“Learn Object-Oriented Java the Hard Way” is ©2015–2016 Graham Mitchell