JUnit 5 with useJUnitPlatform()
The test task of the java plugin runs whatever test framework the build points it at. JUnit 5 is a platform with its own launcher, and Gradle 9 no longer carries that launcher, so a build names it. Three lines of dependencies and one line of configuration are the whole setup.
The three lines
settings.gradle
rootProject.name = 'shop'
build.gradle
plugins {
id 'java'
}
repositories {
mavenLocal()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.14.3'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher:1.14.3'
}
tasks.named('test') {
useJUnitPlatform()
}
junit-jupiter is the aggregate: the API a test imports, the engine that runs it and the parameterized support. It is a testImplementation dependency, so the main code cannot see it. useJUnitPlatform() tells the test task to hand the tests to the JUnit Platform instead of JUnit 4.
A test
src/main/java/com/example/Calc.java
package com.example;
public final class Calc {
public static int add(int a, int b) {
return a + b;
}
}
src/test/java/com/example/CalcTest.java
package com.example;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class CalcTest {
@Test
@DisplayName("2 + 2 is 4")
void addsTwoNumbers() {
assertEquals(4, Calc.add(2, 2));
}
@Test
void addsNegativeNumbers() {
assertEquals(-5, Calc.add(-2, -3));
}
}
gradle test
gradle test --console=plain --offline --no-daemon
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
BUILD SUCCESSFUL in 25s
3 actionable tasks: 3 executed
Two tests ran and the log says nothing about them, because a passing test prints nothing by default. The filtering lesson turns the per-test lines on, and the report lesson opens the HTML the task wrote.
Why the launcher is spelled out
Until Gradle 8 the test task carried the JUnit Platform launcher inside Gradle itself. In Gradle 9 it does not: the launcher is a dependency of the build, and a build that names only junit-jupiter fails with a message that says the launcher is missing. The line looks redundant next to the aggregate, and it is the one line a build ported from Gradle 8 has to add.
A BOM is the shorter way to keep the two versions in step: the platform lesson writes the two dependencies without a version at all.
Related
- A failing test: the same project with one wrong assertion.
- The test reports: the HTML and the XML the task writes.
- JUnit 5: the framework, with a course of its own.
Article author: Arthur Isaev