Skip to main content

How to set up a Kotlin project with Gradle and JUnit

Set up a Kotlin project with Gradle: scaffold with gradle init, configure the Kotlin plugin and JUnit platform, add kotlin(test), write code and tests, and run with the Gradle wrapper.

Difficulty
Beginner
Duration
40 minutes
Steps
6

What Gradle and Kotlin give you

Gradle is a flexible JVM build tool that uses a declarative build script, which can itself be written in Kotlin. Kotlin is a concise, null-safe language that runs on the JVM and interoperates with Java. JUnit 5 provides the test framework. Together they form a modern, type-safe JVM stack.

Prerequisites

  • JDK 17 or later
  • Gradle, or use the generated Gradle wrapper
  • A terminal

Steps

1. Initialize a Gradle project

mkdir greeter && cd greeter
gradle init --type kotlin-library --dsl kotlin

This scaffolds the build script, source folders, and a wrapper.

2. Configure the Kotlin build

The generated build.gradle.kts applies the Kotlin plugin. Ensure JUnit is enabled.

plugins { kotlin("jvm") version "1.9.24" }

tasks.test { useJUnitPlatform() }

3. Add the test dependency

dependencies {
    testImplementation(kotlin("test"))
}

The kotlin("test") artifact wires Kotlin's assertions to JUnit 5.

4. Write Kotlin code

// src/main/kotlin/Greeter.kt
fun greet(name: String?): String = "hello, ${name ?: "world"}"

5. Write a JUnit 5 test

// src/test/kotlin/GreeterTest.kt
import kotlin.test.Test
import kotlin.test.assertEquals

class GreeterTest {
    @Test
    fun greetsName() {
        assertEquals("hello, Ada", greet("Ada"))
    }

    @Test
    fun greetsWorldOnNull() {
        assertEquals("hello, world", greet(null))
    }
}

6. Run the build and tests

./gradlew test

The wrapper downloads the correct Gradle version and runs the tests.

Verification

Run ./gradlew test and confirm the build succeeds with both tests passing. Open the HTML test report under build/reports/tests to inspect results. Break an assertion and confirm the build fails clearly.

Next Steps

Add parameterized tests, configure code coverage, enable the Kotlin compiler's explicit API mode, and run ./gradlew check in continuous integration.

Prerequisites

  • JDK 17+ installed
  • Gradle installed or the wrapper
  • Basic command line familiarity

Steps

  • 1
    Initialize a Gradle project
  • 2
    Configure the Kotlin build
  • 3
    Add the test dependency
  • 4
    Write Kotlin code
  • 5
    Write a JUnit 5 test
  • 6
    Run the build and tests