当前位置: 首页 > news >正文

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

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

package testsimport "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 stringsep   stringwant  []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 stringsep   stringwant  []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)}})}
}

在这里插入图片描述

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

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


http://www.mrgr.cn/news/8868.html

相关文章:

  • 【机器学习】 1. 总览介绍
  • openai whisper使用
  • 在VBA中调用Adobe Acrobat或Reader的命令行工具,实现PDF自动打印 (‾◡◝)
  • Spring Boot日志
  • 排序算法【希尔排序】
  • Activity的启动流程(AndroidU)
  • 【互动直播】支付能力视角与年龄的调节作用—推文分享—2024-08-25
  • 手把手教你搭建 Go 项目
  • 考研资讯平台
  • 【数据结构-前缀异或和】1442. 形成两个异或相等数组的三元组数目
  • 华为Cloud连接配置
  • 圈子论坛小程序搭建教程,系统快速部署上线指南,支持文章、源码、链接等上传
  • 【UE5】Groom毛发系统的基本使用——给小白人添加头发
  • 配置PXE预启动执行环境:使用PXE装机服务器网络引导装机
  • Spring Web MVC入门
  • 【LLM大模型论文日更】| 格式胜过内容:揭示大型语言模型的提示效应
  • CST软件仿真案例:圆极化平板天线仿真01
  • 基于虚拟下垂控制的分布式电源并网建模仿真
  • 深度学习入门-第4章-神经网络的学习
  • 【redis】包含部署+主从复制+高可用+cluster