JUnit5學習之六:參數化測試(Parameterized Tests)基礎

歡迎訪問我的GitHub

https://github.com/zq2599/blog_demos

內容:所有原創文章分類彙總及配套源碼,涉及Java、Docker、Kubernetes、DevOPS等;

關於《JUnit5學習》系列

《JUnit5學習》系列旨在通過實戰提升SpringBoot環境下的單元測試技能,一共八篇文章,鏈接如下:

  1. 基本操作
  2. Assumptions類
  3. Assertions類
  4. 按條件執行
  5. 標籤(Tag)和自定義註解
  6. 參數化測試(Parameterized Tests)基礎
  7. 參數化測試(Parameterized Tests)進階
  8. 綜合進階(終篇)

本篇概覽

  • 本文是《JUnit5學習》系列的第六篇,一起來實戰強大參數化測試(Parameterized Tests),即多次執行同一個測試方法,每次使用不同的參數;
  • 由於參數化測試功能強大,內容也比前幾篇的知識點多,爲了方便大家閱讀和實踐,這裏分爲《基礎》和《進階》兩篇來介紹,本篇以學習參數化測試(Parameterized Tests)的基礎知識爲主,包含以下內容:
  1. 極速體驗;
  2. 版本依賴;
  3. ValueSource數據源
  4. null、空字符串數據源
  5. 枚舉數據源
  6. 方法數據源
  7. Csv格式數據源
  8. Csv文件數據源

源碼下載

  1. 如果您不想編碼,可以在GitHub下載所有源碼,地址和鏈接信息如下表所示:
名稱 鏈接 備註
項目主頁 https://github.com/zq2599/blog_demos 該項目在GitHub上的主頁
git倉庫地址(https) https://github.com/zq2599/blog_demos.git 該項目源碼的倉庫地址,https協議
git倉庫地址(ssh) [email protected]:zq2599/blog_demos.git 該項目源碼的倉庫地址,ssh協議
  1. 這個git項目中有多個文件夾,本章的應用在<font color="blue">junitpractice</font>文件夾下,如下圖紅框所示:

在這裏插入圖片描述

  1. <font color="blue">junitpractice</font>是父子結構的工程,本篇的代碼在<font color="red">parameterized</font>子工程中,如下圖:

在這裏插入圖片描述

極速體驗

  1. 現在,咱們以最少的步驟體驗最簡單的參數化測試;
  2. 在父工程junitpractice裏新建名爲<font color="red">parameterized</font>的子工程,pom.xml內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.bolingcavalry</groupId>
        <artifactId>junitpractice</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>parameterized</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>parameterized</name>
    <description>Demo project for parameterized expirence in Spring Boot junit</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.junit</groupId>
                <artifactId>junit-bom</artifactId>
                <version>5.7.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>

    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  1. 新建測試類<font color="red">HelloTest.java</font>,在這個位置:<font color="blue">junitpractice\parameterized\src\test\java\com\bolingcavalry\parameterized\service\impl</font>,內容如下:
package com.bolingcavalry.parameterized.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertTrue;

@SpringBootTest
@Slf4j
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class HelloTest {

    @Order(1)
    @DisplayName("多個字符串型入參")
    @ParameterizedTest
    @ValueSource(strings = { "a", "b", "c" })
    void stringsTest(String candidate) {
        log.info("stringsTest [{}]", candidate);
        assertTrue(null!=candidate);
    }
}    
  1. 執行該測試類,結果如下圖:

在這裏插入圖片描述 5. 從上圖可見執行參數化測試需要兩步:首先用<font color="blue">@ParameterizedTest</font>取代<font color="blue">@Test</font>,表名此方法要執行參數化測試,然後用<font color="blue">@ValueSource</font>指定每次測試時的參數來自字符串類型的數組:{ "a", "b", "c" },每個元素執行一次; 6. 至此,咱們已體驗過最簡單的參數化測試,可見就是想辦法使一個測試方法多次執行,每次都用不同的參數,接下來有關參數化測試的更多配置和規則將配合實戰編碼逐個展開,一起來體驗吧;

版本要求

  • 先看看<font color="blue">SpringBoot-2.3.4.RELEASE</font>間接依賴的<font color="blue">junit-jupiter-5.6.2</font>版本中,<font color="red">ParameterizedTest</font>的源碼,如下圖紅框所示,此時的ParameterizedTest還只是<font color="red">體驗版</font>:

在這裏插入圖片描述

  • 再看看<font color="red">junit-jupiter-5.7.0</font>版本的ParameterizedTest源碼,此時已經是<font color="blue">穩定版</font>了:

在這裏插入圖片描述

  • 綜上所述,如果要使用參數化測試,最好是將junit-jupiter升級到<font color="red">5.7.0或更高版本</font>,如果您的應用使用了SpringBoot框架,junit-jupiter是被spring-boot-starter-test間接依賴進來的,需要排除這個間接依賴,再手動依賴進來才能確保使用指定版本,在pom.xml中執行如下三步操作:
  1. dependencyManagement節點添加junit-bom,並指定版本號:
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.junit</groupId>
      <artifactId>junit-bom</artifactId>
      <version>5.7.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
  1. 排除spring-boot-starter-test和junit-jupiter的間接依賴關係:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
    </exclusion>
  </exclusions>
</dependency>
  1. 添加junit-jupiter依賴,此時會使用dependencyManagement中指定的版本號:
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <scope>test</scope>
</dependency>
  1. 如下圖,刷新可見已經用上了5.7.0版本:

在這裏插入圖片描述

  • 版本問題解決了,接下來正式開始學習Parameterized Tests,先要了解的是有哪些數據源;

ValueSource數據源

  1. ValueSource是最簡單常用的數據源,支持以下類型的數組:
    short

    byte

    int

    long

    float

    double

    char

    boolean

    java.lang.String
    
    java.lang.Class
  1. 下面是整形數組的演示:
    @Order(2)
    @DisplayName("多個int型入參")
    @ParameterizedTest
    @ValueSource(ints = { 1,2,3 })
    void intsTest(int candidate) {
        log.info("ints [{}]", candidate);
        assertTrue(candidate<3);
    }
  1. 從上述代碼可見,入參等於3的時候assertTrue無法通過,測試方法會失敗,來看看實際執行效果,如下圖:

在這裏插入圖片描述

null、空字符串數據源

  1. 在用字符串作爲入參時,通常要考慮入參爲null的情況,此時ValueSource一般會這樣寫:
@ValueSource(strings = { null, "a", "b", "c" })
  1. 此時可以使用@NullSource註解來取代上面的null元素,下面這種寫法和上面的效果一模一樣:
    @NullSource
    @ValueSource(strings = { "a", "b", "c" })
  1. 執行結果如下圖紅框,可見null作爲入參被執行了一次:

在這裏插入圖片描述 4. 與@NullSource代表null入參類似,@EmptySource代表<font color="blue">空字符串</font>入參,用法和執行結果如下圖所示:

在這裏插入圖片描述 5. 如果想同時用null和空字符串做測試方法的入參,可以使用<font color="blue">@NullAndEmptySource</font>,用法和執行結果如下圖所示:

在這裏插入圖片描述

枚舉數據源(EnumSource)

  1. EnumSource可以讓一個枚舉類中的全部或者部分值作爲測試方法的入參;
  2. 創建枚舉類Types.java,用於接下來的實戰,如下,很簡單隻有三個值:
public enum Types {
    SMALL,
    BIG,
    UNKNOWN
}
  1. 先嚐試用Types的每個值作爲入參執行測試,可見只要添加@EnumSource即可,JUnit根據測試方法的入參類型知道要使用哪個枚舉:
    @Order(6)
    @DisplayName("多個枚舉型入參")
    @ParameterizedTest
    @EnumSource
    void enumSourceTest(Types type) {
        log.info("enumSourceTest [{}]", type);
    }
  1. 執行結果如下圖所示:

在這裏插入圖片描述 5. 如果不想執行枚舉的所有值,而只要其中一部分,可以在<font color="blue">name屬性</font>中指定:

@EnumSource(names={"SMALL", "UNKNOWN"})
  1. 執行結果如下圖所示:

在這裏插入圖片描述 7. 也可以指定哪些值<font color="red">不被執行</font>,此時要添加mode屬性並設置爲<font color="blue">EXCLUDE</font>(mode屬性如果不寫,默認值是INCLUDE,前面的例子中就是默認值):

@EnumSource(mode= EnumSource.Mode.EXCLUDE, names={"SMALL", "UNKNOWN"})
  1. 執行結果如下,可見SMALL和UNKNOWN都<font color="red">沒有執行</font>:

在這裏插入圖片描述

方法數據源(MethodSource)

  1. @MethodSource可以指定一個方法名稱,該方法返回的元素集合作爲測試方法的入參;
  2. 先來定義一個方法,該方法一般是static類型(否則要用@TestInstance修飾),並且<font color="blue">返回值是Stream類型</font>:
    static Stream<String> stringProvider() {
        return Stream.of("apple1", "banana1");
    }
  1. 然後,測試方法用@MethodSource,並指定方法名<font color="blue">stringProvider</font>:
    @Order(9)
    @DisplayName("靜態方法返回集合,用此集合中每個元素作爲入參")
    @ParameterizedTest
    @MethodSource("stringProvider")
    void methodSourceTest(String candidate) {
        log.info("methodSourceTest [{}]", candidate);
    }
  1. 上面的stringProvider方法和測試方法methodSourceTest在同一個類中,如果它們不在同一個類中,就要指定靜態方法的整個package路徑、類名、方法名,如下所示,類名和方法名之間用<font color="blue">#</font>連接:
@Order(10)
    @DisplayName("靜態方法返回集合,該靜態方法在另一個類中")
    @ParameterizedTest
    @MethodSource("com.bolingcavalry.parameterized.service.impl.Utils#getStringStream")
    void methodSourceFromOtherClassTest(String candidate) {
        log.info("methodSourceFromOtherClassTest [{}]", candidate);
    }
  1. 如果不在@MethodSource中指定方法名,JUnit會尋找和測試方法同名的靜態方法,舉例如下,靜態方法<font color="blue">methodSourceWithoutMethodNameTest</font>會被作爲測試方法的數據來源:
    static Stream<String> methodSourceWithoutMethodNameTest() {
        return Stream.of("apple3", "banana3");
    }

    @Order(11)
    @DisplayName("靜態方法返回集合,不指定靜態方法名,自動匹配")
    @ParameterizedTest
    @MethodSource
    void methodSourceWithoutMethodNameTest(String candidate) {
        log.info("methodSourceWithoutMethodNameTest [{}]", candidate);
    }
  1. 執行結果如下:

在這裏插入圖片描述

Csv格式數據源(CsvSource)

  1. 前面的測試方法入參都只有一個,在面對多個入參的測試方法時,@CsvSource就派上用場了,演示代碼如下所示,可見數據是普通的CSV格式,每條記錄有兩個字段,對應測試方法的兩個入參:
    @Order(12)
    @DisplayName("CSV格式多條記錄入參")
    @ParameterizedTest
    @CsvSource({
            "apple1, 11",
            "banana1, 12",
            "'lemon1, lime1', 0x0A"
    })
    void csvSourceTest(String fruit, int rank) {
        log.info("csvSourceTest, fruit [{}], rank [{}]", fruit, rank);
    }
  1. 執行結果如下,通過日誌可以確定,每條記錄的兩個字段能匹配到測試方法的兩個入參中:

在這裏插入圖片描述

  1. 另外@CsvSource還提供了一個屬性<font color="blue">nullValues</font>,作用是將指定的字符串識別爲null,下面這個設置就是把CSV數據中所有的<font color="red">NIL</font>識別爲null,再傳給測試方法:
    @Order(13)
    @DisplayName("CSV格式多條記錄入參(識別null)")
    @ParameterizedTest
    @CsvSource(value = {
            "apple2, 21",
            "banana2, 22",
            "'lemon2, lime2', 0x0A",
            "NIL, 3" },
            nullValues = "NIL"
    )
    void csvSourceWillNullTokenTest(String fruit, int rank) {
        log.info("csvSourceWillNullTokenTest, fruit [{}], rank [{}]", fruit, rank);
    }
  1. 執行結果如下,可見字符串<font color="red">NIL</font>到測試方法後已變成<font color="blue">null</font>:

在這裏插入圖片描述

Csv文件數據源

  1. @CsvSource解決了測試方法入參有多個字段的問題,但是把作爲入參的測試數據寫在源文件中似乎不合適,尤其是數據量很大的情況下,這種場景適合用@CsvFileSource,該註解用於指定csv文件作爲數據源,注意<font color="blue">numLinesToSkip</font>屬性指定跳過的行數,可以用來跳過表頭:
    @Order(14)
    @DisplayName("CSV文件多條記錄入參")
    @ParameterizedTest
    @CsvFileSource(files = "src/test/resources/two-column.csv", numLinesToSkip = 1)
    void csvFileTest(String country, int reference) {
        log.info("csvSourceTest, country [{}], reference [{}]", country, reference);
    }
  1. 在<font color="blue">src/test/resources/</font>創建文件two-column.csv,內容如下:
Country, reference
Sweden, 1
Poland, 2
"United States of America", 3
  1. 上述代碼執行結果如下,代碼中沒有測試數據,顯得更加簡潔一些:

在這裏插入圖片描述

期待《進階》篇

  • 至此,咱們隊JUnit5的參數化測試(Parameterized)有了初步的瞭解,可以通過各種數據源註解給測試方法制造更多的參數,但僅掌握這些還是不夠的,依然有一些問題待解決,例如更自由的數據源定製、跟完善的多字段處理方案等等,下一篇《進階》咱們一起來體驗更多參數化測試的高級功能;

你不孤單,欣宸原創一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 數據庫+中間件系列
  6. DevOps系列

歡迎關注公衆號:程序員欣宸

微信搜索「程序員欣宸」,我是欣宸,期待與您一同暢遊Java世界... https://github.com/zq2599/blog_demos

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章