Spring Boot 2.2.x Junit4 升級為Junit5 后的變化、對比 找不到 org.junit.jupiter.api.Test


遇到的問題:
使用 maven 創建了一個 parent 項目 A,其 pom.xml 繼承 parent 為 spring-boot-starter-parent 2.1.10。

然后創建 module 項目 B,使用 spring initializr 構建項目,用的是 IDEA,當時沒有選 Spring Boot 版本,結果默認使用的是 2.2.1。

創建成功之后的pom.xml如下 Spring Boot 2.2 之后的 pom.xml。

修改項目 B 的 pom 的 parent 為 A,結果測試類報錯,找不到 org.junit.jupiter.api.Test

原因:
spring boot 2.2 之前使用的是 Junit4 而后續的使用的是Junit5,導致缺少包。

解決方案:
將父工程 A 的 parent 升級為 spring-boot-starter-parent 2.2.1,如果使用了依賴管理 dependencyManagement,需要把里面的 spring-boot-starter-test 版本號改為 與 parent 對應的 2.2.1。

當然,也可以直接指定 module工程B 的 spring-boot-starter-test 版本號改為 與 parent 對應的 2.2.1

Spring Boot 2.2 前后區別

Spring Boot 2.2 之前的測試類

package com.example.demo1;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo1ApplicationTests {
 
    @Test
    public void contextLoads() {
    }
 
}

Spring Boot 2.2 之前的 pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.10.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>   
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Spring Boot 2.2 之后的測試類

package com.example.demo;
 
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
@SpringBootTest
class DemoApplicationTests {
 
    @Test
    void contextLoads() {
    }
 
}

Spring Boot 2.2 之后的 pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<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>


官方文檔說明
鏈接:
https://docs.spring.io/spring-boot/docs/2.2.x/reference/html/spring-boot-features.html#boot-features-testing


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM