本篇文章主要介紹 Go 語言 testify 套件進行單元測試

  • 建立主程式
  • 建立測試

建立主程式

  1. 建立一個專案 「Project」,在路徑 D:/Workspace/Go 執行 go mod init Project,建立後路徑如下

    1
    2
    Go
    └─ go.mod
  2. 建立 sum.go 填入以下內容

    1
    2
    3
    4
    5
    package main

    func Sum(a int, b int) int {
    return a + b
    }
  3. 建立 main.go 填入以下內容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    package main

    import (
    "fmt"
    )

    func main() {
    fmt.Println(Sum(5, 7))
    }
  4. 編譯程式碼

    1
    2
    # From within D:/Workspace/Go
    go build .
  5. 執行程式碼

    1
    2
    # From within D:/Workspace/Go
    Project.exe
  6. 最後路徑如下

    1
    2
    3
    4
    5
    Go
    ├─ go.mod
    ├─ main.go
    ├─ Project.exe
    └─ sum.go

建立測試

  1. 安裝 testify

    1
    go get -u github.com/stretchr/testify
  2. 建立 sum_test.go 填入以下內容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    package main

    import (
    "testing"

    "github.com/stretchr/testify/assert"
    )

    func TestSum(t *testing.T) {
    assert.Equal(t, Sum(1, 2), 3)
    }
  3. 執行測試

    1
    2
    # From within D:/Workspace/Go
    go test -v
  4. 最後路徑如下

    1
    2
    3
    4
    5
    6
    7
    Go
    ├─ go.mod
    ├─ go.sum
    ├─ main.go
    ├─ Project.exe
    ├─ sum.go
    └─ sum_test.go