Running JUnit5 and JUnit4 tests in the same project with Maven

What I learned today — 9 March 2018

Niel de Wet
1 min readMar 9, 2018

JUnit5 is a great project with many good reasons to start using it now that it has reached Generally Available status. Using it in an existing project with JUnit4 tests is pretty simple, but has a few gotcha’s. Here is an abridged pom.xml that works for me:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>project-with-junit4-junit5</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<maven.version>3.0.0</maven.version>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>

<junit.version>4.12</junit.version>
<junit.jupiter.version>5.1.0</junit.jupiter.version>
<junit.vintage.version>5.1.0</junit.vintage.version>
<junit.platform.version>1.1.0</junit.platform.version>
</properties>

<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<!-- For old JUnit4 tests -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<dependencies>
<!-- let surefire run JUnit 4 but also JUnit 5 tests -->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
<!-- let JUnit vintage engine run JUnit 3 or JUnit 4 tests -->
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit.vintage.version}</version>
</dependency>
<!-- let JUnit 5 engine run JUnit 5 tests -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

The version of the surefire plugin is important, JUnit5 is not compatible with all versions. Version 2.19.1 works.

--

--

Responses (1)