0
0
JunitHow-ToBeginner ยท 3 min read

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.
  • test block (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 java plugin, so Gradle does not know how to compile or run tests.
  • Forgetting to add useJUnitPlatform() in the test block, which is required for JUnit 5.
  • Using the wrong dependency scope; use testImplementation for 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

StepDescriptionExample
1Apply Java pluginplugins { id 'java' }
2Add JUnit 5 dependencytestImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'
3Set repositoryrepositories { mavenCentral() }
4Enable JUnit Platformtest { useJUnitPlatform() }
5Write tests insrc/test/java
6Run testsgradle 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.