在 JVM 平台中用 JUnit 测试代码——教程
This tutorial will show you how to write a simple unit test and run it with the Gradle build tool.
The example in the tutorial has the kotlin.test library under the hood and runs the test using JUnit.
To get started, first download and install the latest version of IntelliJ IDEA.
Add dependencies
Open a Kotlin project in IntelliJ IDEA. If you don’t already have a project, create one.
Specify JUnit 5 as your test framework when creating your project.

Open the
build.gradle(.kts)file and add the following dependency to the Gradle configuration. This dependency will allow you to work withkotlin.testandJUnit:
【Kotlin】
dependencies {// Other dependencies.testImplementation(kotlin("test"))}
【Groovy】
dependencies {// Other dependencies.testImplementation 'org.jetbrains.kotlin:kotlin-test'}
- Add the
testtask to thebuild.gradle(.kts)file:
【Kotlin】
tasks.test {useJUnitPlatform()}
【Groovy】
test {useJUnitPlatform()}
If you created the project using the New Project wizard, the task will be added automatically.
Add the code to test it
Open the
main.ktfile insrc/main/kotlin.The
srcdirectory contains Kotlin source files and resources. Themain.ktfile contains sample code that will printHello, World!.Create the
Sampleclass with thesum()function that adds two integers together:class Sample() {fun sum(a: Int, b: Int): Int {return a + b}}
Create a test
In IntelliJ IDEA, select Code | Generate | Test… for the
Sampleclass.
Specify the name of the test class. For example,
SampleTest.IntelliJ IDEA creates the
SampleTest.ktfile in thetestdirectory. This directory contains Kotlin test source files and resources.You can also manually create a
*.ktfile for tests insrc/test/kotlin.
Add the test code for the
sum()function inSampleTest.kt:- Define the test
testSum()function using the @Test annotation. - Check that the
sum()function returns the expected value by using the assertEquals() function.
import kotlin.test.Testimport kotlin.test.assertEqualsinternal class SampleTest {private val testSample: Sample = Sample()@Testfun testSum() {val expected = 42assertEquals(expected, testSample.sum(40, 2))}}
- Define the test
Run a test
Run the test using the gutter icon.

You can also run all project tests via the command-line interface using the
./gradlew checkcommand.
Check the result in the Run tool window:

The test function was executed successfully.
Make sure that the test works correctly by changing the
expectedvariable value to 43:@Testfun testSum() {val expected = 43assertEquals(expected, classForTesting.sum(40, 2))}
Run the test again and check the result:

The test execution failed.
下一步做什么
Once you’ve finished your first test, you can:
- Try to write another test using other kotlin.test functions. For example, you could use the assertNotEquals() function.
- Create your first application with Kotlin and Spring Boot.
- Watch these video tutorials on YouTube, which demonstrate how to use Spring Boot with Kotlin and JUnit 5.
