JaCoCo Javaコードカバレッジ+ Mavenの例
Jacocoは、アプリケーションのコードカバレッジを測定するために使用されます。 このチュートリアルでは、MavenでJacocoを構成する方法と、Jacocoを使用してコードカバレッジレポートを表示する方法を理解します。
使用されるテクノロジー:
-
エクリプスマーズ
-
Maven 3.3.9
-
Java 8
1. Eclipse Create Maven Java Project
1.1 In Eclipse create a Maven project File->New->Project->Maven Project
, Select create a simple project and click on next
1.2 Enter groupId & artifactId as shown in below screen and click on finish.
2. プロジェクト構造
プロジェクトには次のコンポーネントがあります
-
算術演算クラスのサンプル
-
算術演算のサンプルJUnitテストクラス
-
JunitとJacocoの依存関係を持つ
pom.xml
3. pom.xml
pom.xml
に示すようにJUnitとJacocoを構成します
pom.xml
4.0.0 com.techfou MathOperations 0.0.1-SNAPSHOT Mathematical Operations 0.7.5.201505241946 4.12 junit junit ${junit.version} test org.apache.maven.plugins maven-compiler-plugin 3.6.1 true true 1.8 1.8 org.jacoco jacoco-maven-plugin ${jacoco.version} prepare-agent prepare-agent report prepare-package report post-unit-test test report target/jacoco.exec target/jacoco-ut target/jacoco.exec
4. 算術演算クラスのサンプル
このクラスメソッドでは、2つの整数パラメーターを受け入れ、合計を返す「add」が作成されます。
ArithmeticOperations.java
package math.operation; public class ArithmeticOperations { public Integer add(Integer a, Integer b) { return a+b; } }
5. サンプルの算術演算Junitテストクラス
「追加」メソッド用のテストケースが作成されます。
ArithmeticOperationsTest.java
package math.operation; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ArithmeticOperationsTest { @Test public void testAdd() { ArithmeticOperations operations = new ArithmeticOperations(); Integer actual = operations.add(2, 6); Integer expected = 8; assertEquals(expected, actual); } }
6. アプリケーションを実行
「プロジェクト」→「実行」→「Mavenテスト」を右クリックします。 Jacoco出力レポートは、jacoco-utフォルダーの下のターゲットディレクトリに生成されます。
7. 出力
7.1 To see the output go to target directory and open index.html from jacoco-ut folder in browser. クラスArithmeticOperations
の全体的なレポートを以下に示します
7.2 Clicking on each method in above figure gives detailed report. ここでは、ユニットテストでカバーされている行を示す緑色の線が表示されます。
完了しました。
ソースコードをダウンロード
ダウンロード–jacoco-maven-example.zip(2 KB)