[Java] [JUnit 5 support] Write a test using JUnit 5 with Spring boot 2.2, 2.3

less than 1 minute read

This article describes “Spring boot2.2 or later, JUnit5 compatible”. If you can refer to the following purposes!

  1. Update from Spring boot 2.1 or lower to 2.2 or higher
  2. Transfer from JUnit4 to JUnit5
  3. When writing JUnit5, I want to exclude JUnit4 in advance

0. Assumption

environment

  • Java 8 ~ (Spring boot 2.2 or higher supports Java 8 and 11)
  • Spring boot 2.2 ~

Good knowledge to know

  • Starting from Spring boot 2.2, JUnit5 is the default
  • JUnit4 and JUnit5 are basically not compatible
  • Currently JUnit 4 and 5 can coexist (will disappear soon)

1. Dependencies for using JUnit5

  • things to do -exclude junit-vintage-engine (because of the dependency that makes JUnit4 work)

Example 1. Maven

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

Example 2. Gradle

testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group:'org.junit.vintage', module:'junit-vintage-engine'
}
  • @RunWith is obsolete -Supported …Deleted or changed to @ExtendWith
  • The import source of @Test has changed -Before support … import org.junit.Test; -After support … import org.junit.jupiter.api.Test;
  • @Before is obsolete -Supported … changed to @BeforeEach or @BeforeAll

(reference)

↓ This is a reference site