Thursday, September 11, 2014

Getting Cobertura Code Coverage with Java 8 using Maven

I recently upgraded a few projects to Java 8 and the Cobertura instrumentation stopped working with a bunch of warnings similar to the following:
 [cobertura] WARN [main] net.sourceforge.cobertura.instrument.CoberturaInstrumenter - Unable to instrument file /home/user/workspace/cache/target/generated-classes/cobertura/com/test/cache/Cache.class  
 java.lang.IllegalArgumentException  
      at org.objectweb.asm.ClassReader.<init>(Unknown Source)  
      at org.objectweb.asm.ClassReader.<init>(Unknown Source)  
      at org.objectweb.asm.ClassReader.<init>(Unknown Source)  
      at net.sourceforge.cobertura.instrument.CoberturaInstrumenter.instrumentClass(CoberturaInstrumenter.java:147)  
      at net.sourceforge.cobertura.instrument.CoberturaInstrumenter.instrumentClass(CoberturaInstrumenter.java:121)  
      at net.sourceforge.cobertura.instrument.CoberturaInstrumenter.addInstrumentationToSingleClass(CoberturaInstrumenter.java:234)  
      at net.sourceforge.cobertura.instrument.Main.addInstrumentationToSingleClass(Main.java:298)  
      at net.sourceforge.cobertura.instrument.Main.addInstrumentation(Main.java:307)  
      at net.sourceforge.cobertura.instrument.Main.parseArguments(Main.java:399)  
      at net.sourceforge.cobertura.instrument.Main.main(Main.java:421)  
I'm not sure what the state of the Cobertura and cobertura-maven-plugin projects are, but for my projects I found that manually setting the version for the ASM Core dependency to 5.0.3 gets Cobertura working again. Here are the important parts from the pom.xml:
<build>  
    <plugins>  
        <plugin>  
            <groupId>org.apache.maven.plugins</groupId>  
            <artifactId>maven-compiler-plugin</artifactId>  
            <version>3.1</version>  
            <configuration>  
                <source>1.8</source>  
                <target>1.8</target>  
            </configuration>  
        </plugin>  
        <plugin>  
            <groupId>org.codehaus.mojo</groupId>  
            <artifactId>cobertura-maven-plugin</artifactId>  
            <version>2.6</version>  
            <dependencies>  
                <dependency>  
                    <groupId>org.ow2.asm</groupId>  
                    <artifactId>asm</artifactId>  
                    <version>5.0.3</version>  
                </dependency>  
            </dependencies>  
        </plugin>  
    </plugins>  
</build>