Intellij Idea使用Junit5的@DisplayName不生效


確認 IDEA 版本

首先我的 IDEA 版本是 2019.2,是支持使用 Junit5 的,所以應該不需要安裝額外的插件。

Idea 官方博客表示支持JUnit5測試框架是IntelliJ IDEA 2016.2新特性的其中一個:

Using JUnit 5 in IntelliJ IDEA

國內的媒體也翻譯並轉發了這篇報道:

搜狐:在IntelliJ IDEA中使用JUnit5

那問題就在於我使用 Junit5 的方式不正確?

問題重現

首先我當時參考的是這篇文章: here

於是乎,我的依賴是這樣的

<dependencies>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <version>1.7.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.7.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <version>5.7.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>

然后,我在 src/test/java 中創建了 FirstTest.java

import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.ArrayList;
import java.util.List;

public class FirstTest {

    @Test
    @DisplayName("首次測試")
    public void first_test() {
        List<String> list = new ArrayList<String>();
        list.add("張三");
        list.add("李四");
        list.add("王五");
        Assert.assertEquals(3, list.size());
    }
}

執行結果,本想看看 Junit5 的 DisplayName 的效果,但是結果卻和 Junit4 一致?Junit5 的 @DisplayName 完全沒起作用啊?

原因竟在 import

找了好久,我才發現問題的所在。原因竟然是導入 @Test 包錯誤

√ 正確導入示例: import org.junit.jupiter.api.Test;

× 錯誤導入示例: import org.junit.Test;

結語

這個問題,當時花了將近 10 min 才找到答案。感覺還是對 Junit5 的三個子項目 JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage 理解不深。
其實,我還發現新建一個 Java8 編譯的 Maven 項目時,只需要依賴 Jupiter 就夠了。

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.7.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>

如果只依賴 Jupiter, 就不會引用到 Junit4 的 org.junit.Test 了,也就不會出現這個低級錯誤了。


免責聲明!

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



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