サンプルアプリケーションの作成
まず、Mavenプロジェクトを作成し、メインのロジッククラスを作成します。ここでは、シンプルな条件分岐を含む計算処理を実装した MathUtility クラスを src/main/java 配下に定義します。
package com.example.calc;
public class MathUtility {
public MathUtility() {
}
/**
* 基礎値とボーナス値を計算するメソッド
* @param base 基礎値
* @param bonus ボーナス値
* @return 計算結果
*/
public int compute(int base, int bonus) {
int result = 0;
// 基礎値が100を超える場合のみ加算処理を行う
if (base > 100) {
result = base + bonus;
} else {
result = base * 2;
}
return result;
}
}
単体テストクラスの実装
次に、先ほど作成したクラスの動作を検証するためのJUnitテストクラスを作成します。今回は src/test/java ディレクトリ(Mavenの標準構造)に MathUtilityTest クラスを作成します。このテストでは else ブロックのロジックのみを検証し、カバレッジが100%にならない状態を意図的に作ります。
package com.example.calc;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MathUtilityTest {
@Test
public void testComputeBaseBelowThreshold() {
MathUtility util = new MathUtility();
// baseが100以下のケースをテスト(elseブランチ)
int actual = util.compute(50, 10);
// 50 * 2 = 100 期待される値
assertEquals(100, actual);
}
}
Maven設定ファイル(pom.xml)の構成
pom.xml には、Coberturaプラグインの設定を追加します。Jenkins環境でビルドされることを前提に、env.BUILD_NUMBER プロパティが存在する場合にのみプラグインが有効になるようプロファイルを設定します。レポート形式はXMLを出力するように構成します。
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>coverage-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<profiles>
<!-- Jenkinsの環境変数BUILD_NUMBERが定義されている場合にアクティベート -->
<profile>
<id>ci-build</id>
<activation>
<property>
<name>env.BUILD_NUMBER</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<formats>
<format>xml</format>
</formats>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>cobertura</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Jenkinsの設定と実行
以下の手順でJenkinsのジョブを設定し、カバレッジレポートを生成します。
- プラグインのインストール: Jenkinsの管理画面から「Cobertura Plugin」をインストールし、Jenkinsを再起動します。
- ジョブの作成: 新しいフリースタイル・プロジェクト(またはMavenプロジェクト)のジョブを作成します。
- ビルド設定: ビルド手順「Invoke top-level Maven targets」にて、以下のゴールを設定します。
clean cobertura:cobertura - ビルド後の処理: 「ビルド後の処理」で「Publish Cobertura Coverage Report」にチェックを入れます。「Cobertura xml report pattern」には以下のパターンを指定します。
**/target/site/cobertura/coverage.xml
レポートの確認
設定完了後、ジョブをビルドします。ビルドが成功すると、プロジェクトのトップページまたはジョブの画面から「Cobertura Coverage Report」へのリンクが表示され、各クラスやメソッドの分岐カバレッジを詳細に確認できるようになります。