wancoro blog

学んだことをアウトプットしていきたいと思います

【Junit5】SpringプロジェクトにJacocoを実装する

作業環境

Jacocoとは

テスト時のカバレッジを取得し、HTMLファイルに出力してくれるツールです。 https://www.eclemma.org/jacoco/

実行手順

pom.xml にjacocoのプラグインを追加する。

<dependency>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.3</version>
  <scope>test</scope>
</dependency>

<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.3</version>
     <executions>
       <execution>
         <id>prepare-agent</id>
         <goals>
           <goal>prepare-agent</goal>
         </goals>
       </execution>
       <execution>
         <id>report</id>
         <phase>test</phase>
         <goals>
           <goal>report</goal>
         </goals>
       </execution>
     </executions>
</plugin>

// これがないとカバレッジが反映されなかった
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.0.0-M4</version>
</plugin>

以下コマンドを実行すると、target/site/jacoco/index.htmlが生成される。

mvn clean jacoco:prepare-agent test jacoco:report

IntteliJでindex.htmlを右クリック--> Open in Browserからブラウザを選択 f:id:wancoromochi:20200418150426p:plain すると、ブラウザ上でカバレッジが確認できる。 f:id:wancoromochi:20200418150514p:plain

そのほか

IntelliJRunを実行するとエラーが出るようになってしまった。 f:id:wancoromochi:20200418150818p:plain pom.xmlに以下を追加して解決。

<dependency>
  <groupId>org.junit.vintage</groupId>
  <artifactId>junit-vintage-engine</artifactId>
  <scope>test</scope>
</dependency>