Testing Getters and Setters Considered Useful

Writing unit tests for getters and setters is a good idea because such tests create a regression detection suite.

I sometimes hear the argument that setters and getters are not worth unit testing. The logic goes that as they don’t do anything, there is nothing to test. There is a couple of problems with this attitude:

  • First problem: It uses proof by assertion (“Trust me, this method doesn’t do anything [special]”), which is impossible to verify using automated testing tools such as JUnit.
  • Second problem: The behavior of a setter or a getter may expand in future (such as storing the property in a database), and when it happens, there won’t be a unit test to verify that methods still do what they are supposed to do.

Writing a unit test for setters and getters, as trivial as they are at the moment, creates a regression detection suite. This is important because if future changes to the method break it, the unit test will be there to catch the problem.

To make testing matching pairs of setters and getters easier, I usually test them in a single method testSetGet() instead of the pair testSet() and testGet():

Bean:


public class Bean {
   private String property;
   public String getProperty() {
      return property;
   }
   public void setProperty(final String property) {
      this.property = property;
   }
}

Test method:


 /**
   * Tests setting and getting the property.
   */ 
 public void testSetGetProperty() {
       final String testValue = "Test value";
       assertNull("Initial value should be null", bean.getProperty());
       bean.setProperty(testValue);
       assertEquals("Getter should return value set", testValue, bean.getProperty());
 }

Test getters and setters and enjoy the benefits of the growing regression detection suite and the reliability of well-tested codebase.



Leave a Reply

Your email address will not be published. Required fields are marked *