zoukankan      html  css  js  c++  java
  • 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)
      			}
      		})
      	}
      }
      
  • 相关阅读:
    codechef: ADAROKS2 ,Ada Rooks 2
    codechef: BINARY, Binary Movements
    codechef : TREDEG , Trees and Degrees
    ●洛谷P1291 [SHOI2002]百事世界杯之旅
    ●BZOJ 1416 [NOI2006]神奇的口袋
    ●CodeForce 293E Close Vertices
    ●POJ 1741 Tree
    ●CodeForces 480E Parking Lot
    ●计蒜客 百度地图的实时路况
    ●CodeForces 549F Yura and Developers
  • 原文地址:https://www.cnblogs.com/2bjiujiu/p/14118227.html
Copyright © 2011-2022 走看看