問題現象
Spring Bootプロジェクトで単体テストを作成する際に、JUnit 4.13.2以上のバージョンを使用しています。
Mavenが単体テストを自動実行するために、Maven SurefireまたはMaven Failsafeプラグインの導入が必要です。
プロジェクトで使用しているmaven-surefire-pluginのバージョンは2.22.2で、mvn clean packageコマンドでのパッケージング時、単体テストが実行されません。
一連のテストの結果、maven-surefire-pluginのバージョンを2.21以下にすると単体テストが正常に実行されることが判明しました。
解決策
上記の分析から、最も直接的な解決策はmaven-surefire-pluginのバージョンを下げることです。
しかし、プログラマーとして、そこで手を止めるわけにはいきません。
maven-surefire-pluginプラグインの動作原理を見てみましょう。デフォルトでは、JUnitを見つけてテストケースを実行するために以下のロジックを使用します:
if the JUnit version in the project >= 4.7 and the parallel attribute has ANY value
use junit47 provider
if JUnit >= 4.0 is present
use junit4 provider
else
use junit3.8.1
デフォルトの方法でJUnitパッケージを検索しない場合は、手動で依存関係を指定することができます:
1. JUnit4.7以上の場合の明示的な宣言
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.22.2</version>
</dependency>
</dependencies>
</plugin>
2. JUnit 4.0(含む)からJUnit4.7(含まない)の場合の宣言
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit4</artifactId>
<version>2.22.2</version>
</dependency>
</dependencies>
</plugin>
3. JUnit 3.8(含む)からJUnit 4.0(含まない)の場合の宣言
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit3</artifactId>
<version>2.22.2</version>
</dependency>
</dependencies>
</plugin>
4. JUnit 3.8以下の場合
残念ながら、surefireはこれほど低いバージョンのJUnitはサポートしていません。JUnitのバージョンをアップグレードしてください。