How does Cobertura work with JUnit?
Asked Answered
S

2

14

I can't understand how Cobertura cooperates with JUnit. As I understood cobertura modifies compiled byte code and inserts in this byte code its own commands. Ok. After that we run Junit framework and give it our tests to run. Could anyone explain at what points cobertura gets the information which of its commands were executed?

Semele answered 16/2, 2016 at 10:40 Comment(0)
P
7

Cobertura uses ASM which is a general purpose bytecode manipulation and analysis framework. On every line of java code there are 3 lines added to the existing classes to count things for the report it produces. When Cobertura is included in your classpath and configured correctly and you execute your unit tests, it will produce a datafile called cobertura.ser which is used to produce an xml or html report.

Basic usage: with Maven: http://www.mojohaus.org/cobertura-maven-plugin/usage.html

Prerogative answered 19/2, 2016 at 17:34 Comment(2)
Thank you for your answer. However, I don't understand - we run junit not cobertura. How from these 3 lines off added code reports are generated? Does each of this 3 lined code write to cobertura.ser?Semele
Cobertura is automatically instrumented when you run your unit tests. Its sort of a wrap around thing that happens automatically when you have it configured in your POM (if using Maven) or build.xml file (if using ANT). You're not running it directly but it is being called via the Maven plugin when correctly configured. HTHPrerogative
D
3

Cobertura monitors tests by instrumenting the bytecode with extra statements to log which lines are and are not being reached as the test suite executes.

Cobertura calculates coverage both by the number of lines tested and by the number of branches tested. For a first pass, the difference between these two is not hugely important. Cobertura also calculates the average McCabe's cyclomatic complexity for the class.

If using maven this can be configured in POM:

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <version>2.6</version>
        <configuration>
            <formats>
                <format>html</format>
                <format>xml</format>
            </formats>
        </configuration>
    </plugin>

If using ANT it can be configured with the taskdef statement in the build.xml file:

   <taskdef classpathref="cobertura.classpath" resource="tasks.properties"/>

Reference for ant-cobertura integration can be found at https://github.com/cobertura/cobertura/wiki/Ant-Task-Reference

Deferent answered 23/2, 2016 at 7:30 Comment(1)
Thank you for your answer. However the question is not how to run cobertura with maven or ant. The question is how cobertura cooperates with junit.Semele

© 2022 - 2024 — McMap. All rights reserved.