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)
      			}
      		})
      	}
      }
      
  • 相关阅读:
    MySQL 5.7.18 zip 文件安装过程
    Mysql 自定义随机字符串
    JAVA基本类型和引用类型
    初识JSP
    Java导出错误数据
    时序图的使用习惯
    Redis踩坑
    ES踩坑
    代码规范
    Git在公司的使用流程
  • 原文地址:https://www.cnblogs.com/2bjiujiu/p/14118227.html
Copyright © 2011-2022 走看看