Like many people, I use a coverage analysis tool to measure how much of my code is covered by my unit tests. (For my hobby projects, Coverlipse is my tool of choice; it’s free and reasonably capable.) And I always hate to see my coverage numbers drop just because I’m not bothering to test trivial getter/setter methods. So I wrote a helper class to test the getters and setters for me. Download it here and read on to learn how to use it.
It may be used in exclusive or inclusive mode. In exclusive mode, which is the default, all JavaBeans properties (getter/setter method pairs with matching names) are tested unless they are excluded beforehand. For example:
MyClass objectToTest = new MyClass(); GetterSetterTester gst = new GetterSetterTester(objectToTest); gst.exclude("complexProperty"); gst.exclude("anotherProperty"); gst.test();
In inclusive mode, only properties that are explicitly listed are tested. For example:
new GetterSetterTester(new MyClass()). include("aSimpleProperty"). include("secondProperty"). test();
The second example also illustrates how to call this class in as terse a way as possible.
The following property types are supported:
- All Java primitive types.
- All non-final classes if cglib is on your classpath — this uses cglib even when a no-argument constructor is available because a constructor might have side effects that you wouldn’t want to trigger in a unit test.
- Java 5 enums.
Properties whose types are classes declared “final” are not supported; neither are non-primitive, non-interface properties if you don’t have cglib.
Note for pre-5.0 Java versions: If you’re not using Java 5, you will need to comment out the parts of the code that deal with enums. Search for the string “JAVA5″ (it occurs twice in the code). If there is sufficient demand, I can modify the class to work unmodified on pre-5.0 Java and still support enums, but my assumption is that people won’t need the same copy of the source file to work in both environments very often.