How to run JUnit 5 test in Spring Test Suite?

Viewed 1766

STS: 3.9.7.RELEASE

SpringBoot Project: 2.1.1.RELEASE

Effective POM shows <junit.version>4.12</junit.version>. I was hoping to work with JUnit 5 and I'm also a bit surprised that SpringBoot adds JUnit 4 dependency. Should I add JUnit 5 dependency manually to POM or is it better not to mess with this?

2 Answers

Yes. You have to add JUnit5 manually as spring-boot-starter-test by default include JUnit4 only.

First , exclude JUnit4 from spring-boot-starter-test :

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <!-- Exclude JUnit 4 -->
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
    </dependency>

Then include JUnit5 dependencies:

    <!-- Actual Junit5 implementation. Will transitively include junit-jupiter-api -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- For junit5 parameterised test support -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-params</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- Only required to run junit5 test from IDE -->
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <scope>test</scope>
    </dependency>

Update On 14-Feb-2020 : Since Spring Boot 2.2 , JUnit5 is included by default.

Consider also excluding: groupId: org.junit.vintage, artifactId: junit-vintage-engine, which is also present in later versions of spring-boot-starter-test, and which also contains JUnit4 classes.

Related