Kotlin/Gradle/JUnit starter project
A quick tutorial to bootstrap a Kotlin project using Gradle. Optionally, JUnit can also be added.
--
1. Create a project
- Download and install IntelliJ Community, free for Java/Kotlin projects. Alternatively, you can use IntelliJ Ultimate EAP (if available, no subscription is required).
- Go to “File” ⇀ “New project”. In the wizard:
a. Write a Name and pick a Location;
b. Activate “Create Git repository”;
c. Language: “Kotlin”;
d. Build system: “Gradle”;
e. JDK: Pick any JDK. If you’re unsure which to pick, go to “Download JDK” (in the dropdown) and select the latest “Oracle OpenJDK”. If you get a warning, decrease one version because Gradle may not support it yet.
f. Gradle DSL: Pick “Kotlin” as Gradle DSL. Since we’re using Kotlin, it makes sense that the Gradle DSL is Kotlin. - Press “Create”.
2. Setup Git
To ensure you don’t lose your work and can always go back in time, ensure you set up Git — even if only locally.
- If you haven’t picked “Create Git repository” before, start a new git repository (
git init
). - Create (or edit) a
.gitignore
file with the following content, and commit all the changes:
/.gradle
/.idea
/build
3. Update Gradle/Kotlin
The IDE wizard doesn’t apply the latest versions of Gradle and Kotlin, so let’s do it manually.
- Upgrade Gradle to its latest version:
./gradlew wrapper --gradle-version=LATEST_GRADLE
Check the latest version on the Gradle releases page. - Upgrade Kotlin at
build.gradle.kts
Check the latest version on the Kotlin releases page.
plugins {
kotlin("jvm") version "LATEST_KOTLIN"
}
3. You may need to click on the second icon to force a Gradle refresh:
4. You may need to update the toolchain to match your JVM that’s used to run the project:
kotlin {
jvmToolchain(17)
}
4. Set up JUnit
JUnit gets automatically set up for you. You're supposed to see this at build.gradle.kts
:
dependencies {
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}
- Create a dummy test (
src/test/kotlin/DummyTest.kt
):
import kotlin.test.Test
import kotlin.test.assertTrue
class TestAmazonCart {
@Test
fun `everything is fine`() {
assertTrue(true)
}
}
Notice that we’re using the imports from Kotlin Test which abstract JUnit but are the same.
2. Run it (there’s a ️▶️ near the test) to prove that the JUnit setup is good:
You can also run the tests with ./gradlew test
📝 We’ve used IntelliJ IDEA to create a new Kotlin project. However, there’s an alternative way that relies on Gradle.