go mod 與單元測試

go mod

為解決go模組間的相互引用,可以將go mod理解成j2ee中的pom文件。

創建mod

默認模組名

go mod init

指定模組名

go mod init <model-name>

引入其他模組

比如說需要引入 gin 模組。

  1. 首先需要進入模組所在目錄,運行命令:
 go get -u github.com/gin-gonic/gin
  1. 查看mod文件

可以看到會將相關的依賴拉取下來,這樣就能在自己的模組中使用這些包了。

module org.golearn.basic

go 1.14

require (
	github.com/gin-gonic/gin v1.6.3 // indirect
	github.com/go-playground/validator/v10 v10.3.0 // indirect
	github.com/golang/protobuf v1.4.2 // indirect
	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
	github.com/modern-go/reflect2 v1.0.1 // indirect
	golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 // indirect
	google.golang.org/protobuf v1.24.0 // indirect
	gopkg.in/yaml.v2 v2.3.0 // indirect
)

go 單元測試

創建源文件和測試文件

├── test
│   ├── calc.go
│   └── calc_test.go

calc.go

package main

func Add(a, b int) int{
	return a + b
}

func Sub(a, b int) int {
	return a - b
}

func Mul(a, b int) int {
	return a * b
}

calc_test.go

package main

import  "testing"

func TestAdd(t *testing.T) {
	t.Helper()
	if ans := Add(1, 2); ans != 3 {
		t.Errorf("1 + 2 expected be 3, but %d got", ans)
	}
}

func TestMul(t *testing.T) {
	//if ans := Mul(10, 20); ans != 100 {
	//	t.Errorf("10 * 20 expected be 600, but %d got", ans)
	//}

	// 子測試
	// 正數
	t.Run("正數相乘結果", func(t *testing.T) {
		if ans := Mul(2, 3); ans != 6{
			t.Errorf("10 * 20 expected be 6, but %d got", ans)
		}
	})

	// 子測試-負數
	t.Run("負數相乘結果", func(t *testing.T) {
		if ans := Mul(-20, 3); ans != -60 {
			t.Errorf("10 * 20 expected be -60, but %d got", ans)
		}
	})

}

func TestSub(t *testing.T) {
	if ans := Sub(10, 1); ans != 9 {
		t.Errorf("10 - 1 expected be 9, but %d got ", ans)

	}
}

// 多個子測試場景
func TestMul2(t *testing.T) {

	mulCases := []struct{
		Name string
		Num1, Num2, Expect int
	}{
		{"pos", 1, 2, 2},
		{"neg", 1, -2, -2},
		{"zero", 0, -2, 10},

	}

	for _, r := range mulCases {
		t.Run(r.Name, func(t *testing.T) {
			t.Helper()
			if ans := Mul(r.Num1, r.Num2); ans != r.Expect {
				t.Fatalf("%d * %d expected %d, but %d got",
					r.Num1, r.Num2, r.Expect, ans)
			}
		})
	}

}

//
/*
測試用例
1. 在相同的包路徑中創建 xxx_test.go文件
2. 編寫測試用例
3. 運行測試用例,查看測試用例中所有函數的運行結果 go test -v
*/

運行測試用例

go test -v  
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
=== RUN   TestMul
=== RUN   TestMul/正數相乘結果
=== RUN   TestMul/負數相乘結果
--- PASS: TestMul (0.00s)
    --- PASS: TestMul/正數相乘結果 (0.00s)
    --- PASS: TestMul/負數相乘結果 (0.00s)
=== RUN   TestSub
--- PASS: TestSub (0.00s)
=== RUN   TestMul2
=== RUN   TestMul2/pos
=== RUN   TestMul2/neg
=== RUN   TestMul2/zero
    TestMul2/zero: calc_test.go:55: 0 * -2 expected 10, but 0 got
--- FAIL: TestMul2 (0.00s)
    --- PASS: TestMul2/pos (0.00s)
    --- PASS: TestMul2/neg (0.00s)
    --- FAIL: TestMul2/zero (0.00s)
FAIL
exit status 1
FAIL    org.golearn.basic/test  0.005s