How to use Junit 4 in a Spring Boot 2.6 project

Downgrade spring-boot-starter-test to use Junit 4 instead of 5

Saeed Zarinfam
2 min readFeb 12, 2022

As you know, from Spring Boot 2.2 when you add the spring-boot-starter-test dependency to your Spring Boot project, your project will be configured to use JUnit 5. It does not make sense to downgrade the JUnit version to 4 when you start a Spring Boot project from scratch with version 2.6 but what if you force to upgrade a legacy project to use Spring Boot 2.6 (for example from version 2.1) while that project has a bunch of tests that wrote using JUnit 4? As a temporary solution, maybe you want to downgrade the JUnit version to 4 for now and then after a while, you can migrate all those tests in the future to JUnit 5. But how?

The solution

You just need to exclude the junit-jupiter-engine and junit-vintage-engine from the spring-boot-starter-test dependency and then add JUnit 4 dependency in your pom:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</exclusion>
<exclusion>
<groupId>org.junit.vintage</groupId>…

--

--

Saeed Zarinfam

A lifelong Learner, Old Programmer πŸ‘¨β€πŸ’»β˜•οΈ Technical Writer ✍️ Late bloomer 🐌 Football lover ⚽️ Father πŸ‘§ https://devstips.substack.com/