JUnitのMavenセットアップ – JUnit 4およびJUnit 5

JUnit 4とJUnit 5は完全に異なるフレームワークです。両方とも同じ目的を果たしますが、JUnit 5は完全にゼロから書き直されたテストフレームワークです。JUnit 4のAPIは使用していません。ここでは、MavenプロジェクトでJUnit 4とJUnit 5をセットアップする方法について説明します。

JUnit Mavenの依存関係

JUnit 4を使用する場合、以下の単一の依存関係が必要です。

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
	<scope>test</scope>
</dependency>

JUnit 5はいくつかのモジュールに分かれており、JUnit 5でテストを書くには少なくともJUnit PlatformJUnit Jupiterが必要です。また、JUnit 5はJava 8以上のバージョンが必要です。

<dependency>
	<groupId>org.junit.jupiter</groupId>
	<artifactId>junit-jupiter-engine</artifactId>
	<version>5.2.0</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.junit.platform</groupId>
	<artifactId>junit-platform-runner</artifactId>
	<version>1.2.0</version>
	<scope>test</scope>
</dependency>

パラメータ化テストを実行したい場合、追加の依存関係を追加する必要があります。

<dependency>
	<groupId>org.junit.jupiter</groupId>
	<artifactId>junit-jupiter-params</artifactId>
	<version>5.2.0</version>
	<scope>test</scope>
</dependency>

Mavenビルド中のJUnitテスト

テストをMavenビルド中に実行したい場合は、pom.xmlファイルでmaven-surefire-pluginプラグインを設定する必要があります。 JUnit 4:

<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-surefire-plugin</artifactId>
			<version>2.22.0</version>
			<dependencies>
				<dependency>
					<groupId>org.apache.maven.surefire</groupId>
					<artifactId>surefire-junit4</artifactId>
					<version>2.22.0</version>
				</dependency>
			</dependencies>
			<configuration>
				<includes>
					<include>**/*.java</include>
				</includes>
			</configuration>
		</plugin>
	</plugins>
</build>

JUnit 5:

<build>
	<plugins>
		<plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-surefire-plugin</artifactId>
           <version>2.22.0</version>
           <dependencies>
               <dependency>
                   <groupId>org.junit.platform</groupId>
                   <artifactId>junit-platform-surefire-provider</artifactId>
                   <version>1.2.0</version>
               </dependency>
           </dependencies>
           <configuration>
           	<additionalClasspathElements>
           		<additionalClasspathElement>src/test/java/</additionalClasspathElement>
           	</additionalClasspathElements>
           </configuration>
       </plugin>
	</plugins>
</build>

JUnit HTML レポート

Maven Surefire プラグインは、テキストと XML レポートを生成しますが、maven-surefire-report-plugin を使用して HTML ベースのレポートを生成することもできます。以下の設定は、JUnit 4 と JUnit 5 の両方で動作します。

<reporting>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-surefire-report-plugin</artifactId>
			<version>2.22.0</version>
		</plugin>
	</plugins>
</reporting>

mvn site コマンドを実行するだけで、HTML レポートが target/site/ ディレクトリに生成されます。それが、maven プロジェクトの JUnit セットアップのクイックな概要です。

Source:
https://www.digitalocean.com/community/tutorials/junit-setup-maven