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