Migrating to JUnit 5

Introduction

JUnit 5

VocabHunter

Changing Gradually

dependencies {
testCompile 'junit:junit:4.12'
....
}
dependencies {
testCompile 'org.junit.vintage:junit-vintage-engine:4.12.0'
....
}
testCompile 'org.junit.jupiter:junit-jupiter-api:5.0.0'
testCompile 'org.junit.jupiter:junit-jupiter-params:5.0.0'
testRuntime 'org.junit.jupiter:junit-jupiter-engine:5.0.0'

Gradle Plugin

buildscript {
....
dependencies {
....
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0'
}
}
subprojects {
....
apply plugin: 'org.junit.platform.gradle.plugin'
....
}

Mockito

@BeforeEach
public void initMocks() {
MockitoAnnotations.initMocks(this);
}

Code Coverage with Jacoco

subprojects {
....
jacoco {
toolVersion = '0.7.9'
}
jacocoTestReport {
reports {
xml.enabled true
xml.destination "${buildDir}/reports/jacoco/report.xml"
}
}
....
}
subprojects {
....
jacoco {
toolVersion = '0.7.9'
applyTo junitPlatformTest
}
if (it.name in ['core', 'gui']) {
jacocoTestReport {
reports {
xml.enabled true
xml.destination file("${buildDir}/reports/jacoco/report.xml")
}
}
}
junitPlatformTest {
jacoco {
destinationFile = file("$buildDir/jacoco/test.exec")
}
}
....
}

JVM Arguments

@BeforeAll
public static void setupSpec() throws Exception {
if (Boolean.getBoolean("headless")) {
....
}
....
}
test {
....
if (!project.hasProperty("noHeadless")) {
jvmArgs "-Dheadless=true"
}
}
junitPlatformTest {
if (!project.hasProperty("noHeadless")) {
jvmArgs "-Dheadless=true"
}
}

Excluding Tests

test {
if (project.hasProperty("skipGuiTests")) {
exclude 'io/github/vocabhunter/gui/main/GuiTest*'
}
....
}
junitPlatform {
if (project.hasProperty("skipGuiTests")) {
filters {
excludeClassNamePattern 'io.github.vocabhunter.gui.main.GuiTest'
}
}
}

PMD Problems

<rule ref="rulesets/java/migrating.xml">
<exclude name="JUnit4TestShouldUseBeforeAnnotation"/>
<exclude name="JUnit4TestShouldUseAfterAnnotation"/>
<exclude name="JUnit4TestShouldUseTestAnnotation"/>
</rule>

Tricks for Updating Tests

assertEquals("Line number count", lineCount, lines.size());
assertEquals(lineCount, lines.size(), "Line number count");
find * -name '*Test.java' -print0 \
| xargs -0 grep -c '^[^i].*assert' >asserts.csv
find * -name '*Test.java' -print0 \
| xargs -0 grep -c '@Test' >tests.csv

Final Words

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store