How do I add JUnit to a Gradle project?

To add JUnit to a Gradle project, add the JUnit dependency to your build.gradle or build.gradle.kts file and configure Gradle to use the JUnit Platform.

If you use Groovy Gradle: build.gradle

For JUnit 5, add:

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'
}

test {
    useJUnitPlatform()
}

If you use Kotlin Gradle: build.gradle.kts

plugins {
    java
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
}

tasks.test {
    useJUnitPlatform()
}

Example JUnit 5 Test

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class CalculatorTest {

    @Test
    void addsNumbers() {
        assertEquals(4, 2 + 2);
    }
}

Place test files under:

src/test/java

For example:

src/test/java/org/kodejava/CalculatorTest.java

Run Tests

From the command line:

./gradlew test

On Windows:

gradlew test

If You Need JUnit 4 Instead

Use this dependency:

dependencies {
    testImplementation 'junit:junit:4.13.2'
}

For most new Gradle projects, prefer JUnit 5 with junit-jupiter.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.