Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bean testing framework

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.?

like image 703
Paul Schifferer Avatar asked Dec 01 '22 05:12

Paul Schifferer


2 Answers

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.

like image 164
duffymo Avatar answered Dec 05 '22 07:12

duffymo


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()
    ));
}
like image 35
orien Avatar answered Dec 05 '22 07:12

orien