LoginSignup
1
4

More than 3 years have passed since last update.

jacoco導入

Last updated at Posted at 2019-04-22

jacocoを導入して、TestNG実行時のカバレッジを取得します。

カバレッジ取得の仕組み

jacocoとCoberturaしか触ったことがありませんが、どちらも以下のような流れとなります。詳しくは知りません。

  • instrumentというプログラムでクラスファイルを書き換え、実行時に通った行番号がファイル出力されるようにする
  • ファイル出力された行番号をもとにカバレッジを計算

なので、instrumentで書き換えたクラスファイルをもとにアーカイブを作ってしまったりすると非常に残念なことになります。ご注意ください。

準備

Mavenがラクです。
実行時に計測(on-the-fly instrumentation)することもできますが、PowerMock使用時にカバレッジが0%になってしまうものがいくつかありました。なので、事前にクラスファイルに手を入れておく方法(offline instrumentation)を採用しています。

今回はNetBeans IDE 8.2を使用していますが、IDE側の不具合で結果レポートが正しく表示されなかったため、あえて旧バージョンの0.8.1を導入しています。

pom.xml(dependencies)
<dependency>
    <!-- これがないとOffline Instrumentが動かない -->
    <groupId>org.jacoco</groupId>
    <artifactId>org.jacoco.agent</artifactId>
    <version>0.8.1</version>
    <scope>test</scope>
    <classifier>runtime</classifier>
</dependency>
pom.xml(build/plugins)
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M3</version>
    <configuration>
        <systemPropertyVariables>
            <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
        </systemPropertyVariables>
        <!-- ↓これがないとスタックトレースが出ない -->
        <trimStackTrace>false</trimStackTrace>
    </configuration>
</plugin>
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <!-- 0.8.2 @NetBeans IDE 8.2だと「コード・カバレージ」が記録されない -->
    <version>0.8.1</version>
    <executions>
        <execution>
            <id>default-instrument</id>
            <goals>
                <goal>instrument</goal>
            </goals>
        </execution>
        <execution>
            <id>default-restore-instrumented-classes</id>
            <goals>
                <goal>restore-instrumented-classes</goal>
            </goals>
        </execution>
        <execution>
            <id>default-report</id>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>

テスト実行

Mavenでテスト実行し、終わったらコード・カバレージの「レポートを表示」してください。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4