0
0
JunitHow-ToBeginner ยท 3 min read

How to Add JUnit Dependency in Gradle for Testing

To add JUnit dependency in Gradle, include testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3' in your build.gradle file inside the dependencies block. This adds JUnit 5 for writing and running tests with Gradle.
๐Ÿ“

Syntax

In your build.gradle file, add the JUnit dependency inside the dependencies block using the testImplementation configuration. This tells Gradle to include JUnit only for test compilation and runtime.

  • testImplementation: Scope for test dependencies.
  • 'org.junit.jupiter:junit-jupiter:5.9.3': The group, artifact, and version of JUnit 5.
groovy
dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
}
๐Ÿ’ป

Example

This example shows a simple Gradle build file with the JUnit 5 dependency added. It also configures the test task to use the JUnit Platform.

groovy
plugins {
    id 'java'
}

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

test {
    useJUnitPlatform()
}
Output
BUILD SUCCESSFUL in 1s 2 actionable tasks: 2 executed
โš ๏ธ

Common Pitfalls

Common mistakes when adding JUnit dependency in Gradle include:

  • Using implementation instead of testImplementation, which adds JUnit to the main code instead of tests.
  • Forgetting to add useJUnitPlatform() in the test block, causing tests not to run.
  • Using an outdated JUnit version or mixing JUnit 4 and 5 dependencies.
groovy
dependencies {
    // Wrong: adds JUnit to main code
    implementation 'org.junit.jupiter:junit-jupiter:5.9.3'
}

test {
    // Missing this causes tests not to run
    // useJUnitPlatform()
}

// Correct way:
dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
}

test {
    useJUnitPlatform()
}
๐Ÿ“Š

Quick Reference

TermDescription
testImplementationDependency scope for test code only
'org.junit.jupiter:junit-jupiter:5.9.3'JUnit 5 library coordinates
useJUnitPlatform()Configures Gradle to run JUnit 5 tests
โœ…

Key Takeaways

Add JUnit dependency using testImplementation in build.gradle.
Always include useJUnitPlatform() in the test block to run JUnit 5 tests.
Use the latest stable JUnit version for best compatibility.
Avoid adding JUnit to main implementation scope to keep dependencies clean.
Check for version conflicts if mixing JUnit 4 and 5.