JUnit インストールガイド

JUnitはMaven、Gradle、直接JARダウンロードなど、複数の方法でプロジェクトに追加できます。以下では各バージョンのインストール方法を詳しく説明します。

JUnit 5のインストール

Maven設定

pom.xmlに以下の依存関係を追加します:

<!-- JUnit Jupiter アグリゲーターモジュール -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.14.3</version>
    <scope>test</scope>
</dependency>

Maven Surefire Pluginでテストを実行する場合、以下の設定も追加します:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.5.2</version>
</plugin>

Gradle設定

build.gradleに依存関係を追加:

testImplementation 'org.junit.jupiter:junit-jupiter:5.14.3'

テストの実行:

test {
    useJUnitPlatform()
}

直接JARをダウンロード

Maven Centralから必要なJARファイルをダウンロード:

  • junit-jupiter-api:JUnit Jupiter API
  • junit-jupiter-engine:JUnit Jupiterエンジン
  • junit-platform-console-standalone:スタンドアロンコンソールランチャー

JUnit 4のインストール

Maven設定

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

Gradle設定

testImplementation 'junit:junit:4.13.2'

直接JARをダウンロード

Maven Centralからjunit-4.13.2.jarをダウンロード:

https://repo1.maven.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar

JUnit Vintageのインストール

JUnit 5プラットフォームでJUnit 4テストを実行するには、Vintageエンジン依存関係を追加:

Maven

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

Gradle

testImplementation 'org.junit.vintage:junit-vintage-engine:5.14.3'

バージョン互換性

  • JUnit 5はJava 8以上が必要
  • JUnit 4はJava 5以上が必要
  • JUnit Vintage 5.14.3はJUnit 4.12以上が必要

インストール確認

テストクラスを作成してインストールを確認:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class SampleTest {
    @Test
    void testExample() {
        assertEquals(2, 1 + 1);
    }
}

テストを実行:

mvn test
# または
gradle test