Is there a framework or library available that, when given a JavaBean, will "put it through its paces," i.e., test all the getters and setters, validate that a property matches the getters and setters, etc.?
Personally, I don't think that's the hardest part of testing. It'd be possible to do via reflection, but that's not what makes testing worthwhile.
The hard part is figuring out all the possible inputs, for "happy path" and erroneous situations, making sure that exceptions are thrown when they should be, etc.
Your Java Bean should be implementing equals and hashCode. I'd worry more about tests to check the equals contract: null equals, reflexive, symmetric, transitive, and not equals. Those aren't trivial.
Getters and setters are the least of your problems. When people talk about code coverage standards of 70% or better they often say that getters and setters can be left out.
While I agree that there are bigger problems to solve, there are cases for testing Java bean methods. Large teams teams working on large codebases can run into problems. I've seen several cases of copy/paste error leading to getters or setters working on the wrong property. Forgetfulness can lead to hashCode and equals methods becoming inconsistent. Finding bugs in this simple code can be very frustrating.
Bean Matchers is a library that can help in this regard. It provides a series of Hamcrest matchers for reflectively testing Java beans. For example:
@Test
public void testBean() {
assertThat(MyBean.class, allOf(
hasValidBeanConstructor(),
hasValidGettersAndSetters(),
hasValidBeanHashCode(),
hasValidBeanEquals(),
hasValidBeanToString()
));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With