Should unit tests be written for getter and setters?

I would say no.

@Will said you should aim for 100% code coverage, but in my opinion that’s a dangerous distraction. You can write unit tests that have 100% coverage, and yet test absolutely nothing.

Unit tests are there to test the behaviour of your code, in an expressive and meaningful way, and getters/setters are only a means to an end. If you tests use the getters/setters to achieve their goal of testing the “real” functionality, then that’s good enough.

If, on the other hand, your getters and setters do more than just get and set (i.e. they’re properly complex methods), then yes, they should be tested. But don’t write a unit test case just to test a getter or setters, that’s a waste of time.

Leave a Comment