JUnitセットアップMaven – JUnit 4とJUnit 5

JUnit4とJUnit5は完全に異なるフレームワークです。両方とも同じ目的を果たしますが、JUnit5は完全に新しく書き直されたテストフレームワークです。JUnit4のAPIは使用していません。ここでは、MavenプロジェクトでJUnit4とJUnit5をどのようにセットアップするかを見ていきます。

JUnitのMaven依存関係

もしJUnit 4を使用したい場合は、以下のように単一の依存関係が必要です。

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

JUnit 5はいくつかのモジュールに分割されており、JUnit 5でテストを書くには少なくともJUnit PlatformとJUnit 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: 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セットアップの簡単なまとめとなります。

コメントを残す 0

Your email address will not be published. Required fields are marked *