Code Coverage with Cobertura and JUnit June 3, 2008Posted by Phill in Testing.
Tags: apache ant, cobertura, code coverage
I hadn’t used code coverage tools much before today. However, after getting to grips with Cobertura, I think I’m a convert!
What I’d like to do here is give a brief overview of what code coverage is, why you would want to use it, and how you can get up and running with code coverage tools in your own projects.
What is Code Coverage?
A Code Coverage tool, in the context of unit testing, basically tells you how much of your code is executing while the tests are running. So, for example, if you have 50 class files and have unit tests for all of them, the Cobertura will tell you how many lines of code per class you are “covering”.
In other words, it tells you how effective your unit tests are – whether you are hitting all the different execution paths through your code in your unit tests. You will probably find that your unit tests are, in fact, missing out various bits of code.
Why should I use it?
Following on from the previous paragraph, it helps you to cover all of your code with unit tests (or at least, all the bits of it which are unit-testable!)
If you can be sure that your unit tests are executing more of your code, you can have greater confidence in your unit tests. Although code coverage tools don’t tell you whether you are executing a method with every single different combination of parameters (and, let’s face it, that would be virtually impossible!) they do at least tell you that you’ve covered all the different methods etc. in your code.
In other words, it’s just a form of QA for your code, a complement to unit tests!
How do I get started?
If you use Ant or Maven (if you’re still using your IDE to build your projects, you really should switch!) it’s fairly easy to integrate Cobertura into your project.
There’s only one little “gotcha” I came across: Cobertura would throw a “NoClassDefFoundError” about org/apache/log4j/Category.
It turned out that I was only provided a link to the cobertura.jar file in my <taskdef> tag, I actually need to include a reference to all required libraries in the <taskdef>.
Other than that, it’s been fairly plain sailing so far!