Wednesday, May 9, 2012

100% Test coverage


When you unit test your code, you do this to make sure your code is correct. To make sure you tested the important you keep track of test coverage with tools like Cobertura. You may ask yourself: “What are the important bits?”, “Do I really need to test everything, even the trivial stuff?”.
I regularly read about developers who demand a 100% test coverage. While I find this a lofty goal, I (and I think many other developers) usually skip the trivial parts of the code, like setters and getters.

public class Address {
 private String street;
 public void setStreet(String street) {
     street = street;
 }
 public String getStreet() {
     return street;
 }
}


It has happened to me that I made a mistake in a setter, which you can glance over pretty easily. I spent considerable time to find this bug and a unit test could have caught that error. Thankfully, it doesn’t occur anymore because Eclipse warns about this.
There is plenty of other code that I think is trivial and not worthy of unit test coverage. Still I surprise myself by introducing bugs in those trivial pieces of code. Should I test even the trivial stuff?

As an experiment, I recently made the effort to reach 100% test coverage and write the tests before/during writing implementing new code (also known as Test Driven Design - TDD). I noticed that this way, you:
  • force yourself to double check the code and review it from a different viewpoint
  • consider different circumstances and input data that the code operates on
  • notice in an early stadium subtle bugs
  • naturally design the code to make testing easier

The surprising conclusion for me is that the process of writing a unit test may be even more important than the resulting unit test.

No comments: