Sunday, September 2, 2007

JUnit Recipes: Practical Methods for Programmer Testing

Download

Extract

The tests are the specification!—If add() and contains() contain defects that cancel one another out, then the test passes and we can argue that the behavior is correct. We hope that future tests will uncover the defects, but if that never happens then we have incorrect code that exhibits correct behavior. If code does the wrong thing but no test fails, does it have a defect? More and more JUnit users say, “No.” They say that “The tests are the specification,” which means that we describe what our code does by providing the tests our code passes. A feature is not present unless there are tests to verify it. Each test is a claim that the code behaves a certain way, so if no test exists to verify that we can add an object twice to the same List, then we cannot assume that that would work. This certainly puts pressure on the programmer to write enough tests!
Just for testing—It is most common to test classes entirely through their public interface. If you adopt this approach as a rule, then you will encounter some cases where you need to add a public method to your class’s interface—often a getter—in order to gain access to the data you need to verify a given behavior. This is a controversial issue among programmers: adding the method seems to break encapsulation “just for testing,” which introduces a trade-off that different people evaluate differently. As with any such situation, it is up to you to try both options and measure the difference.
If your class does not expose readable properties, then you must build some other observable side effect that you can use to verify the correctness of the constructor. It is possible to write a method named isValid() to help verify the sanity of your object without violating the data-hiding principle.
The rule of thumb is this: if the get method simply answers the value of a field, then consider not writing a test for it; however, if the method does anything more complex than that, consider writing the test.

No comments: