当前位置: 代码网 > it编程>前端脚本>Golang > Golang测试func TestXX(t *testing.T)的使用详解

Golang测试func TestXX(t *testing.T)的使用详解

2024年09月08日 Golang 我要评论
一般golang中的测试代码都以xxx_test.go的样式,在命名测试函数的时候以testxx开头。以下是我写的一个单元:package testsimport "strings"func spli

一般golang中的测试代码都以xxx_test.go的样式,在命名测试函数的时候以testxx开头。
以下是我写的一个单元:

package tests
import "strings"
func split(s, sep string) (res []string) {
	i := strings.index(s, sep)
	for i > -1 {
		res = append(res, s[:i])
		s = s[i+len(sep):]
		i = strings.index(s, sep)
	}
	res = append(res, s)
	return
}

第一种测试方法:

func testsplit(t *testing.t) {
	inputs := split("a:b:c", ":")
	want := []string{"a", "b", "c"}
	if !reflect.deepequal(inputs, want) {
		t.errorf("inputs:%v, want:%v", inputs, want)
	}
}

这种直接定义好输入、期望值,进行对比,这种不适合大量数据比较。

第二种测试方法:

func testsplit(t *testing.t) {
	testcases := []struct {
		input string
		sep   string
		want  []string
	}{
		{input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
		{input: "a:b:c", sep: ",", want: []string{"a:b:c"}},
		{input: "abcd", sep: "bc", want: []string{"a", "d"}},
	}
	for _, tc := range testcases {
		got := split(tc.input, tc.sep)
		if !reflect.deepequal(got, tc.want) {
			t.errorf("期望值:%v,实际值:%v\n", tc.want, got)
		}
	}
}

使用结构体测试,然后使用for range遍历,是比较方便的方式,但是如果我的测试数据很多,但是我其中一个测试出现错误了,我现在需要找到那一个,那么这个方式就有点不适用了。

第三种测试方法(推荐使用):

func testsplit(t *testing.t) {
	testcases := map[string]struct {
		input string
		sep   string
		want  []string
	}{
		"one":   {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
		"two":   {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
		"three": {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
		"four":  {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
		"five":  {input: "a:b:c", sep: ":", want: []string{"b", "b", "c"}},
	}
	for name, tc := range testcases {
		t.run(name, func(t *testing.t) {
			got := split(tc.input, tc.sep)
			if !reflect.deepequal(got, tc.want) {
				t.errorf("期望值:%v,实际值:%v", tc.want, got)
			}
		})
	}
}

这里我们使用子测试的方法,主要可以看到第五个测试案例直接报错,信息并显示出来。

同样,也有一些其他的测试方法,后续如果了解更多的话,在这里补上。

到此这篇关于golang测试func testxx(t *testing.t)的使用的文章就介绍到这了,更多相关golang测试func testxx使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com