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