使用 JUnit 在 JVM 中測試程式碼 – 教學
本教學將向您展示如何在 Kotlin/JVM 專案中編寫一個簡單的單元測試,並使用 Gradle 建構工具執行它。
在此專案中,您將使用 kotlin.test 函式庫,並使用 JUnit 執行測試。如果您正在開發多平台應用程式,請參閱 Kotlin 多平台教學。
若要開始,請先下載並安裝最新版本的 IntelliJ IDEA。
新增依賴項
在 IntelliJ IDEA 中開啟 Kotlin 專案。如果您沒有專案,請建立一個。
開啟
build.gradle(.kts)檔案並檢查testImplementation依賴項是否存在。此依賴項允許您使用kotlin.test和JUnit:kotlindependencies { // 其他依賴項。 testImplementation(kotlin("test")) }groovydependencies { // Other dependencies. testImplementation 'org.jetbrains.kotlin:kotlin-test' }將
test任務新增到build.gradle(.kts)檔案中:kotlintasks.test { useJUnitPlatform() }groovytest { useJUnitPlatform() }如果您在建構腳本中使用
useJUnitPlatform()函式,kotlin-test函式庫會自動將 JUnit 5 作為依賴項包含進來。 此設定允許在僅限 JVM 的專案和 Kotlin 多平台 (KMP) 專案的 JVM 測試中存取所有 JUnit 5 API,以及kotlin-testAPI。
以下是 build.gradle.kts 的完整程式碼:
plugins {
kotlin("jvm") version "2.2.21"
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}新增要測試的程式碼
開啟
src/main/kotlin中的Main.kt檔案。src目錄包含 Kotlin 原始檔和資源。Main.kt檔案包含列印Hello, World!的範例程式碼。建立包含
sum()函式的Sample類別,該函式將兩個整數相加:kotlinclass Sample() { fun sum(a: Int, b: Int): Int { return a + b } }
建立測試
在 IntelliJ IDEA 中,為
Sample類別選擇 Code | Generate | Test...:
指定測試類別的名稱。例如,
SampleTest:
IntelliJ IDEA 會在
test目錄中建立SampleTest.kt檔案。 此目錄包含 Kotlin 測試原始檔和資源。您也可以在
src/test/kotlin中手動為測試建立*.kt檔案。在
SampleTest.kt中為sum()函式新增測試程式碼:- 使用
@Test註解 定義testSum()測試函式。 - 透過使用
assertEquals()函式,檢查sum()函式是否回傳預期值。
kotlinimport org.example.Sample import org.junit.jupiter.api.Assertions.* import kotlin.test.Test class SampleTest { private val testSample: Sample = Sample() @Test fun testSum() { val expected = 42 assertEquals(expected, testSample.sum(40, 2)) } }- 使用
執行測試
使用邊欄圖示執行測試:

您也可以透過命令列介面使用
./gradlew check命令執行所有專案測試。在 Run 工具視窗中檢查結果:

測試函式已成功執行。
透過將
expected變數的值更改為 43,確保測試正常運作:kotlin@Test fun testSum() { val expected = 43 assertEquals(expected, classForTesting.sum(40, 2)) }再次執行測試並檢查結果:

測試執行失敗。
接下來
完成第一個測試後,您可以:
- 使用其他
kotlin.test函式編寫更多測試。 例如,使用assertNotEquals()函式。 - 使用 Kotlin Power-assert 編譯器外掛程式改進您的測試輸出。 該外掛程式以環境資訊豐富了測試輸出。
- 使用 Kotlin 和 Spring Boot 建立您的第一個伺服器端應用程式。
