How to Use JUnit with Gradle: Setup and Example
To use
JUnit with Gradle, add the JUnit dependency in your build.gradle file under dependencies and apply the java plugin. Then write test classes in src/test/java and run tests using gradle test.Syntax
To use JUnit with Gradle, you need to apply the java plugin, add JUnit as a test dependency, and configure the test task if needed.
plugins: Applies the Java plugin for compiling and testing Java code.repositories: Defines where to get dependencies (usually Maven Central).dependencies: Adds JUnit library for testing.testblock (optional): Customize test execution options.
groovy
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
}
test {
useJUnitPlatform()
}Example
This example shows a simple JUnit 5 test class and the Gradle setup to run it. The test checks if 2 + 2 equals 4.
java and groovy
// File: src/test/java/com/example/SimpleTest.java package com.example; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class SimpleTest { @Test void addition() { assertEquals(4, 2 + 2, "2 + 2 should equal 4"); } } // File: build.gradle plugins { id 'java' } repositories { mavenCentral() } dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3' } test { useJUnitPlatform() }
Output
> Task :test
BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed
Common Pitfalls
Common mistakes when using JUnit with Gradle include:
- Not applying the
javaplugin, so Gradle does not know how to compile or run tests. - Forgetting to add
useJUnitPlatform()in thetestblock, which is required for JUnit 5. - Using the wrong dependency scope; use
testImplementationfor test libraries. - Placing test classes outside
src/test/java, so Gradle does not find them.
Example of a wrong and right way:
groovy
// Wrong: Missing useJUnitPlatform() test { // no useJUnitPlatform() } // Right: Correct test configuration test { useJUnitPlatform() }
Quick Reference
| Step | Description | Example |
|---|---|---|
| 1 | Apply Java plugin | plugins { id 'java' } |
| 2 | Add JUnit 5 dependency | testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3' |
| 3 | Set repository | repositories { mavenCentral() } |
| 4 | Enable JUnit Platform | test { useJUnitPlatform() } |
| 5 | Write tests in | src/test/java |
| 6 | Run tests | gradle test |
Key Takeaways
Add JUnit 5 dependency with testImplementation in build.gradle.
Apply the java plugin to enable Java compilation and testing.
Use useJUnitPlatform() in the test block to run JUnit 5 tests.
Place test classes under src/test/java for Gradle to find them.
Run tests with the command gradle test.