Unit Testing Setters and Getters

So here’s a question for the masses: is it worth it to unit test simple setters and getters? I would contend that if you can automatically generate the code for them, you can also automatically generate the unit test code that tests them (I smell a new ELisp command coming…). So what code should this tool actually generate? Here’s my first cut, assuming we’re going to use EasyMock: Let’s say the name of the bean is foo, and it has class Foo (we’ll go into unit testing beans of base type in a later post). Also, let’s assume that the code for this in the production class (to distinguish it from the unit test class) looks as follows:

public class Production {
  protected Foo foo;
  public void setFoo(Foo foo) { this.foo = foo; }
  public Foo getFoo() { return this.foo; }
}

Note here that we made the foo field have protected scope, so that our test class (which we are assuming will be in the same package) can access it directly. I claim that these are the tests we need to write:

public class TestProduction extends TestCase {
  protected Foo mockFoo;
  private Production underTest;
  public void setUp() {
    mockFoo = EasyMock.createMock(Foo.class);
    underTest = new Production();
  }
  private void replayMocks() {
    EasyMock.replay(mockFoo);
  }
  private void verifyMocks() {
    EasyMock.verify(mockFoo);
  }
  public testSetsOwnFooForSetFoo() {
    replayMocks();
    underTest.setFoo(mockFoo);
    verifyMocks();
    assertSame(mockFoo, underTest.foo);
  }
  public testReturnsOwnFooForGetFoo() {
    underTest.foo = mockFoo;
    replayMocks();
    Foo result = underTest.getFoo();
    verifyMocks();
    assertSame(mockFoo, result);
  }
}

The replayMocks and verifyMocks are a habit I’ve developed, where I actually replay and verify all the mock objects in the test class, just to make sure I don’t forget any. The use of these methods for these particular test cases actually asserts that there’s no funny business going on here; none of the collaborators for the Production class are being called. So are there any cases this misses? What else would you want to test on your setters and getters? Tomorrow: what to do about base types.