Thursday, January 14, 2010

Cobertura - Ignore Logger Calls

I recently caught the testing bug and try to make sure that all the code I write is well tested and has 100% coverage. I use Cobertura, which is an excellent tool for measuring how much of your code is covered by tests. The coverage report it produces shows you what percentage of packages, classes, methods, lines and conditionals are covered and it highlights, in red, the lines in your source code which are not covered. I can now sleep better at night, knowing that my code is fully covered!

In order to use Cobertura, you just need to add the plugin to your project's POM file. When I first ran Cobertura, I found that it highlighted my logger.debug lines of code, so I had to tell it to ignore all logger calls, as follows:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>cobertura-maven-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <formats>
            <format>html</format>
        </formats>
        <instrumentation>
            <ignores>
                <ignore>org.apache.log4j.*</ignore>
            </ignores>
        </instrumentation>
    </configuration>
    <executions>
        <execution>
            <phase>deploy</phase>
            <goals>
                <goal>cobertura</goal>
            </goals>
        </execution>
    </executions>
</plugin>
You can run it using mvn cobertura:cobertura and then look at the report in target/site/cobertura/index.html.

Cobertura will also highlight some code which is impossible to test. For example, if a class has a private constructor (because it has static methods), then it will highlight the private constructor, even though you can't test it (unless you use reflection and change the constructor's accessibility, but that is going a bit too far!).

3 comments:

  1. 我是天山,等待一輪明月。.........................

    ReplyDelete
  2. Hi

    Finally a realistic example for the usage of the -tag. Do you mind if I use some parts of this blog for the documentation of the cobertura-maven-plugin?

    regards,

    Robert Scholte

    ReplyDelete
  3. Not at all. Glad you found it helpful.

    ReplyDelete