Java Unit Testing – Reality of Test Coverage

javatddunit testing

I am NOT doing test driven development and I write my test classes after the actual code is written. In my current project I have a test coverage (Line coverage) of 70% for 3000 lines of Java code. I am using JUnit, Mockito and Sonar for testing. But I feel that I am not actually covering and catching 70% of the problems that can occur.

So my question is in theory is it possible to have a 100% Line coverage, but in reality it is meaningless because of low quality of the test code and maybe a 40% well written test code is much better than a bad 100% coverage? Or we can always say line coverage more or less gives the percentage of all covered issues?

Best Answer

There are different ways to count coverage. Many tools check which lines are executed by tests, but they don't check that the tests actually test anything. So in theory you could have 100% coverage without a single assert in your tests, in effect testing nothing.

However, you say you have 70% coverage, but you don't catch 70% of problems. That is not uncommon, since quite often small subset of your code contains most of the problems. I think Code Complete says something along the lines that 20% of the code causes 80% of the bugs. That problematic area in your code is usually complex and that is why it's usually untested. So you might have good code coverage but the part that is not covered is the part that needs the tests most.

In this article Martin Fowler says test coverage is not a good measurement for quality of your code. It is a good way to find problematic areas in your code. So in your case, assuming your existing tests are good tests, you now should be able to pinpoint the problem area in your code - the remaining 30%.