คู่มือการติดตั้ง JUnit
สามารถเพิ่ม JUnit เข้าสู่โปรเจกต์ของคุณได้หลายวิธี รวมถึง Maven, Gradle และการดาวน์โหลด JAR โดยตรง ด้านล่างนี้คือคำแนะนำโดยละเอียดสำหรับแต่ละเวอร์ชัน
การติดตั้ง JUnit 5
การตั้งค่า Maven
เพิ่ม dependency ต่อไปนี้ลงใน pom.xml ของคุณ:
<!-- JUnit Jupiter Aggregator Module -->
<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
เพิ่ม dependency ลงใน build.gradle:
testImplementation 'org.junit.jupiter:junit-jupiter:5.14.3'
เพื่อรันโทสต์:
test {
useJUnitPlatform()
}
การดาวน์โหลด JAR โดยตรง
ดาวน์โหลดไฟล์ JAR ที่จำเป็นจาก Maven Central:
- junit-jupiter-api: JUnit Jupiter API
- junit-jupiter-engine: JUnit Jupiter Engine
- junit-platform-console-standalone: Standalone Console Launcher
การติดตั้ง 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 โดยตรง
ดาวน์โหลด junit-4.13.2.jar จาก Maven Central:
https://repo1.maven.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar
การติดตั้ง JUnit Vintage
เพื่อรันโทสต์ JUnit 4 บนแพลตฟอร์ม JUnit 5 ให้เพิ่ม dependency ของ Vintage engine:
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
# or
gradle test
