Kotlin 1.4.32 Help

Test code using JUnit in JVM – tutorial

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

  1. Open a Kotlin project in IntelliJ IDEA. If you don't already have a project, create one.

  2. Open the build.gradle(.kts) file and add the following dependencies to the Gradle configuration. They will allow you to work with kotlin.test and JUnit:

    dependencies { // Other dependencies. testImplementation 'org.jetbrains.kotlin:kotlin-test-junit5' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' }
    dependencies { // Other dependencies. testImplementation(kotlin("test-junit5")) testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.0") }
  3. Add the test task to the build.gradle(.kts) file:

    test { useJUnitPlatform() }
    tasks.test { useJUnitPlatform() }

Add the code to test it

  1. Open the main.kt file in src/main/kotlin.

    The src directory contains Kotlin source files and resources. The main.kt file contains sample code that will print Hello, World!.

  2. Create the Sample class with the sum() function that adds two integers together:

    class Sample() { fun sum(a: Int, b: Int): Int { return a + b } }

Create a test

  1. In IntelliJ IDEA, select Code | Generate | Test... for the Sample class.

    Create a test

  2. Specify the name of the test class. For example, SampleTest.

    IntelliJ IDEA creates the SampleTest.kt file in the test directory. This directory contains Kotlin test source files and resources.

  3. Add the test code for the sum() function in SampleTest.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.Test import kotlin.test.assertEquals internal class SampleTest { private val testSample: Sample = Sample() @Test fun testSum() { val expected = 42 assertEquals(expected, testSample.sum(40, 2)) } }

Run a test

  1. Run the test using the gutter icon.

    Run the test

  2. Check the result in the Run tool window:

    Check the test result. The test passed successfully

    The test function was executed successfully.

  3. Make sure that the test works correctly by changing the expected variable value to 43:

    @Test fun testSum() { val expected = 43 assertEquals(expected, classForTesting.sum(40, 2)) }
  4. Run the test again and check the result:

    Check the test result. The test has been failed

    The test execution failed.

What's next

Once you've finished your first test, you can:

Last modified: 14 March 2021