1. 程式人生 >實用技巧 >其它 >go語言單元測試之一:go語言做單元測試

go語言單元測試之一:go語言做單元測試


技術標籤:go語言單元測試golanggo單元測試unittest

一,演示專案相關資訊

1,地址:

https://github.com/liuhongdi/unittest

2,功能:演示了go做單元測試時的分組測試和子測試

3,專案結構:如圖:

go語言單元測試之一:go語言做單元測試

說明:劉巨集締的go森林是一個專注golang的部落格,
地址:https://blog.csdn.net/weixin_43881017

說明:作者:劉巨集締 郵箱: [email protected]

二,程式碼

1,util/split.go

package util

import "strings"

//字串切分方法
func Split(s, sep string) (result []string) {
	i := strings.Index(s, sep)
	for i > -1 {
		result = append(result, s[:i])
		s = s[i+len(sep):]
		i = strings.Index(s, sep)
	}
	result = append(result, s)
	return
}

2,util/split_test.go

package util

import (
	"reflect"
	"testing"
)

//測試字串切分
func TestSplit(t *testing.T) {
	// test struct
	type testcase struct {
		input string
		sep   string
		excepted  []string
	}
	// 用例: 用map儲存
	cases := map[string]testcase{
		"冒號分隔":      {input: "a:b:c", sep: ":", excepted: []string{"a", "b", "c"}},
		"逗號分隔":   {input: "a:b:c", sep: ",", excepted: []string{"a:b:c"}},
		"字串分割":    {input: "abcd", sep: "bc", excepted: []string{"a", "d"}},
		"中文分隔符位於開始":    {input: "百度員工百度不到時用google", sep: "百度", excepted: []string{"","員工", "不到時用google"}},
		"分隔符last":        {input: "abcd", sep: "d", excepted: []string{"abc", ""}},
	}
	for name, tc := range cases {
		// t.Run():執行子測試
		t.Run(name, func(t *testing.T) {
			got := Split(tc.input, tc.sep)
			if !reflect.DeepEqual(got, tc.excepted) {
				t.Errorf("excepted:%#v, got:%#v", tc.excepted, got)
			}
		})
	}
}

3,main.go

package main

//定義一個加法方法
func add(a, b int) int {
	return a + b
}

4,main_test.go

package main

import (
	"testing"
)
//測試add方法
func TestAdd(t *testing.T) {
	//列出要測試的引數和返回結果
	cases := []struct {
		first    int
		second   int
		excepted int
	}{
		{1, 2, 3},
		{1, 3, 4},
		{2, 2, 4},
	}

	//遍歷,進行測試
	for _, c := range cases {
		result := add(c.first, c.second)
		if result != c.excepted {
			t.Fatalf("add function failed, first: %d, second:%d, execpted:%d, result:%d", c.first, c.second, c.excepted, result)
		}
		/*
		else {
			fmt.Printf("success:first: %d, second:%d, execpted:%d, result:%d \n", c.first, c.second, c.excepted, result)
		}
		 */
	}
}

5,說明:

測試失敗時:
如果使用t.Error/t.Errorf:遇到錯誤不會停,還會繼續執行其他的測試用例

如果使用t.Fatal/t.Fatalf:遇到錯誤即停,不會繼續執行其他的測試用例

大家根據自己的需要選擇

三,測試效果

[email protected]:/data/go/unittest# go test -v ./...
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok  	github.com/liuhongdi/unittest	(cached)
=== RUN   TestSplit
=== RUN   TestSplit/冒號分隔
=== RUN   TestSplit/逗號分隔
=== RUN   TestSplit/字串分割
=== RUN   TestSplit/中文分隔符位於開始
=== RUN   TestSplit/分隔符last
--- PASS: TestSplit (0.00s)
    --- PASS: TestSplit/冒號分隔 (0.00s)
    --- PASS: TestSplit/逗號分隔 (0.00s)
    --- PASS: TestSplit/字串分割 (0.00s)
    --- PASS: TestSplit/中文分隔符位於開始 (0.00s)
    --- PASS: TestSplit/分隔符last (0.00s)
PASS
ok  	github.com/liuhongdi/unittest/util	0.003s

四,檢視go的版本:

[email protected]:/data/go/unittest# go version
go version go1.15.4 linux/amd64