Go-单元测试-Test

单元测试

  • 文件名以 _test.go 结尾
  • 函数名以 Test 开头
  • 函数参数固定 t *testing.T
  • 运行单元测试 go test

Demo

  • 源文件

    package unit
    
    import "strings"
    
    // Splite 分割字符串
    func Splite(str string, delimiter string) []string {
    	reslut := make([]string, 10)
    	index := 0
    	
    	for index >= 0 {
    		index := strings.Index(str, delimiter)
    		if index == -1 {
    			break
    		}
    		reslut = append(reslut, str[:index])
    		str = str[index+1:]
    	}
    	reslut = append(reslut, str[index:])
    	return reslut
    }
    
    
  • 测试文件

    package unit
    
    import (
    	"reflect"
    	"testing"
    )
    
    func TestSplit(t *testing.T) {
    	got := Split("baba", "b")
    	want := []string{"", "a", "a"}
    	if !reflect.DeepEqual(got, want) {
    		t.Errorf("got: %v want:%v", got, want)
    	}
    }
    
  • 测试组与子测试

    package unit
    
    import (
    	"reflect"
    	"testing"
    )
    
    
    func TestSplit(t *testing.T) {
    	// 普通测试
    	got := Split("baba", "b")
    	want := []string{"", "a", "a"}
    	if !reflect.DeepEqual(got, want) {
    		t.Errorf("got: %v want:%v", got, want)
    	}
    
    	// 测试组
    	type testCase struct {
    		str string
    		deli string
    		want []string
    	}
    	testGroup := []testCase{
    		{
    			str:  "abababaaab",
    			deli: "a",
    			want: []string{"a", "b", "c"},
    		},
    	}
    	for _, member := range testGroup{
    		result := Split(member.str, member.deli)
    		if !reflect.DeepEqual(member.want, result) {
    			t.Errorf("param: %v %v want: %v but_get: %v", member.str, member.deli, member.want, result)
    		}
    	}
    
    	// 子测试
    	ChildTestCase := map[string]testCase{
    		"caseOne": {
    			str:  "abababaaab",
    			deli: "a",
    			want: []string{"a", "b", "c"},
    		},
    	}
    	for name, testCase := range ChildTestCase {
    		// 子测试
    		t.Run(name, func(t *testing.T) {
    			result := Split(testCase.str, testCase.deli)
    			if !reflect.DeepEqual(testCase.want, result) {
    				t.Errorf("param: %v %v want: %v but_get: %v", testCase.str, testCase.deli, testCase.want, result)
    			}
    		})
    	}
    }
    
posted @ 2020-12-10 23:58  梦_鱼  阅读(90)  评论(0编辑  收藏  举报