6

I'm wondering how code coverage is measured for Java. For a class my unit test covers most of the functionality but coverage result is about 44%. We use a custom tool at our company and wondering how is the coverage usually measured.

What would be the ideal code coverage percentage to have?

Karthik Kota
  • 423
  • 1
  • 5
  • 10
  • I remember doing this when i was in school, my teacher advised 100% would be ideal, but realistically, I would say anything over 65% should do it. – ryekayo Mar 19 '15 at 00:49
  • 1
    There is no ideal code coverage percentage, you have to set the bar for yourself/your organization. You can aim for 100% and write pointless test cases or be satisfied with 20% if your core functionality that needs to be tested has been covered. It all depends on your use case – tinker Mar 19 '15 at 00:51
  • duplicate:http://stackoverflow.com/questions/90002/what-is-a-reasonable-code-coverage-for-unit-tests-and-why – OPK Mar 19 '15 at 01:28

1 Answers1

3

Dependent on the tool the code coverage might be measured in lines touched by tests or in the number of different branches covered by tests. The metric alone isn't very interesting - look at which lines are not covered. If you're using Eclipse or IntelliJ, there is a code coverage view which you can bring up to show you.

Emma and Cobertura are both decent code coverage tools, but will give different results on the same code+unit tests.

44% code coverage is pretty low.

If you're doing test driven development, then you should be able to achieve 90%+ code coverage, with only weird exceptions and small snippets of file/network access that you exclude from unit testing.

If you've got 44% code coverage, this may be ok. Your code might contain a lot of getters/setters which you're not using right now, but which are handy to have there. Similarly I've noticed that it's not worth exercising all routes through a hashCode or equals method just to appease the coverage tool. If your code is very POJOey with lots of uninteresting boilerplate that was auto-generated, then it's probably no big deal.

Tools like SonarQube are essential for visualising the combination of code coverage hot spots and static code analysis quality metrics.

Don't use quirky in-house tools, find something that's commonly supported.

Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23
  • This seems reasonable. We decided 60% is what we want to achieve now and Like tinker mentioned we want to focus and what code not covered and make a call if add tests for it is necessary. – Karthik Kota Mar 19 '15 at 20:51