Should I test getters and setters?

Indirectly: yes. Directly: probably no.

Generally speaking, this is quite a language-specific question.  In some languages it’s non-issue because of automatic wrapping, whereas enterprise Java code written around year 2000 would be made up of far too many “beans” with auto-generated getters and setters. Testing them like this would feel meaningless and mind-numbing:


@Test
public void getterAndSetterIndeedWork() {
    BeanWithTonsOfProperties testedBean = new BeanWithTonsOfProperties();
    testedBean.setProperty("dubious");
    assertEquals("dubious", testedBean.getProperty());
}

On the other hand, these methods do contribute somehow and need to be tested, which is why an indirect approach is better. Given that the properties of the bean are involved in some meaningful functionality (if not, they should be removed), the typical patterns is that the setters set up the state—in the arrange phase—while the getters query the result— in the assert phase.

Therefore, focus the tests on meaningful operations that make use of the bean. This means that bean won’t be the tested “unit”, which is perfectly fine, since it’s just a carrier of data. Keep in mind that beans that are used mostly for persistence are best tested using integration tests. In conclusion, a combination of unit tests what involve the bean indirectly and integration tests should be sufficient.

Then we have the exception. Sometimes, a getter and a setter will do more than get and set a value. Hopefully this doesn’t happen too often, but in such cases it’s obviously important to write a test for the untypical behavior.

Book References
Read more about these topics in Developer Testing: Building Quality into Software:

  • Chapter 7: Unit Testing, page 81 (this question isn’t answered directly in the book)