1. 程式人生 > 實用技巧 >go 單元測試—只執行指定單元測試函式

go 單元測試—只執行指定單元測試函式

本文介紹go單元測試中,如何執行指定的單元測試函式。

首先看下示例程式碼。

新建目錄utils,目錄有以下檔案

 ll
total 16
-rw-r--r--  1 lanyang  staff   132B 12 31 21:09 add_hint.go
-rw-r--r--  1 lanyang  staff   360B 12 31 21:09 add_hint_test.go

add_hint.go 檔案內容如下:

package utils

func AddPrefix(s string) string {

        return "good " + s
}



func AddSuffix(s string) string {

        return s + "!"
}

add_hint_test.go 檔案內容如下:

package utils

import (
        "testing"
        "strings"
)


func TestAddPrefix(t *testing.T) {

        src := "boy"
        dst := AddPrefix(src)

        if !strings.HasPrefix(dst, "good") {
                t.Fatalf("unexpected dst:%s", dst)
        }
}

func TestAddSufffix(t *testing.T) {
        src := "good"
        dst := AddSuffix(src)

        if !strings.HasSuffix(dst, "!") {
                t.Fatalf("unexpected dst:%s", dst)
        }
}

以上程式碼分別在字串頭部和尾部分別新增字串字首和字尾。

執行當前目錄下所有的單元測試:

go test -v ./
=== RUN   TestAddPrefix
--- PASS: TestAddPrefix (0.00s)
=== RUN   TestAddSufffix
--- PASS: TestAddSufffix (0.00s)
PASS
ok  	_/go_exercise/utils	0.005s

使用-run 指定需要執行的單元測試,支援正則匹配。

例如,只執行 TestAddPrefix 單元測試:

go test -v -run TestAddPrefix ./
=== RUN   TestAddPrefix
--- PASS: TestAddPrefix (0.00s)
PASS
ok  	_/go_exercise/utils	0.006s

例如,執行所有TestAdd開頭的單元測試:

go test -v -run TestAdd ./
=== RUN   TestAddPrefix
--- PASS: TestAddPrefix (0.00s)
=== RUN   TestAddSufffix
--- PASS: TestAddSufffix (0.00s)
PASS
ok  	_/go_exercise/utils	0.006s

綜上,本文簡單介紹了單元測試中如何指定具體的單元測試函式。