当前位置:网站首页>Go unit tests
Go unit tests
2022-08-01 16:02:00 【zakariyaa33】
Unit testing is what is used in the terminalgo testRun our custom test,The code writing requirements are as follows:
Go Language recommendation test files and source code files are placed together,测试文件以 _test.go 结尾,For example we need to test write inmytry.go里的Add函数,The test file name is mytry_test.go
The test function name is prefixed with the function to be testedTest,如要测试Add,The test function is namedTestAdd
When there are multiple functions to be tested,可以用-runto choose to run one of the use cases
go test -run TestAdd
-vThe test results for each use case can be displayed
multiple subtests
//mytry.go
package main
func Add(a int, b int) int {
return a + b
}
func main(){
ret:=Add(1,2)
}
//mytry_test.go
package main
import "testing"
func TestAdd(t *testing.T){
cases:=[]struct{
Name string
A,B,Want int
}{
{
"pos",2,3,5},
{
"neg",2,-4,-2},
{
"zero",2,-2,0},
}
for _,c:=range cases{
t.Run(c.Name,func(t *testing.T){
if Get:=Add(c.A,c.B);Get!=c.Want{
t.Errorf("Name:%s,Want:%d,Get:%d",c.Name,c.Want,Get)
}
})
}
}
go test -run TestAdd -v
=== RUN TestAdd
=== RUN TestAdd/pos
=== RUN TestAdd/neg
=== RUN TestAdd/zero
--- PASS: TestAdd (0.00s)
--- PASS: TestAdd/pos (0.00s)
--- PASS: TestAdd/neg (0.00s)
--- PASS: TestAdd/zero (0.00s)
PASS
ok goProject 0.002s
go test -run TestAdd/zero -v
=== RUN TestAdd
=== RUN TestAdd/zero
--- PASS: TestAdd (0.00s)
--- PASS: TestAdd/zero (0.00s)
PASS
ok goProject 0.002s
帮助函数
t.Helper(),Used to label this function as a helper function,When an error is reported, information to help the caller of the function will be output,rather than the internal information of the helper function.
// calc_test.go
package main
import "testing"
type calcCase struct{
A, B, Expected int }
func createMulTestCase(t *testing.T, c *calcCase) {
// t.Helper()
if ans := Mul(c.A, c.B); ans != c.Expected {
t.Fatalf("%d * %d expected %d, but %d got",
c.A, c.B, c.Expected, ans)
}
}
func TestMul(t *testing.T) {
createMulTestCase(t, &calcCase{
2, 3, 6})
createMulTestCase(t, &calcCase{
2, -3, -6})
createMulTestCase(t, &calcCase{
2, 0, 1}) // wrong case
}
在这里,We created a false test case on purpose,运行 go test,用例失败,The file and line number information where the error occurred will be reported:
$ go test
--- FAIL: TestMul (0.00s)
calc_test.go:11: 2 * 0 expected 1, but 0 got
FAIL
exit status 1
FAIL example 0.007s
可以看到,错误发生在第11行,That is, the helper function createMulTestCase 内部.18, 19, 20line calls this method,We were not able to determine which line the error occurred in the first time.Some helper functions may also be called from different functions,The error messages are all in the same place,Inconvenient to locate the problem.
If we annotate helper functions
func createMulTestCase(c *calcCase, t *testing.T) {
t.Helper()
t.Run(c.Name, func(t *testing.T) {
if ans := Mul(c.A, c.B); ans != c.Expected {
t.Fatalf("%d * %d expected %d, but %d got",
c.A, c.B, c.Expected, ans)
}
})
}
运行 go test,报错信息如下,can be very clearly known,错误发生在第 20 行.
$ go test
--- FAIL: TestMul (0.00s)
calc_test.go:20: 2 * 0 expected 1, but 0 got
FAIL
exit status 1
FAIL example 0.006s
网络测试
Suppose you need to test something API 接口的 Handler 能够正常工作,例如 HelloHandler
func HelloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func TestHelloHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/", nil) //这里的urlIt seems like you can write whatever you want
if err != nil {
fmt.Println(err)
}
ret := httptest.NewRecorder()
HelloHandler(ret, req)
if ret.Body.String() != "hello world" {
fmt.Println("handler erro")
}
}
$ go test -run TestHelloHandler -v
=== RUN TestHelloHandler
--- PASS: TestHelloHandler (0.00s)
PASS
ok goProject 0.002s
测试覆盖率
go test -v -coverprofile=c.out
go tool cover -html=c.out
A page containing the test function will be generated in the browser,Green is covered,Red is not covered
边栏推荐
- 30分钟成为Contributor|如何多方位参与OpenHarmony开源贡献?
- 南京科技大学、中国电子科技第28研究所等联合|MLRIP: Pre-training a military language representation model with informative factual knowledge and professional knowledge base(预训练具有丰富事实知识和专业知识库的军事语言表示模型)
- SyntaxHighlighter带来的字符转义问题
- uniapp 获取cookie与携带cookie请求数据
- 使用Canvas实现网页鼠标签名效果
- 高薪程序员&面试题精讲系列131之Eureka如何实现高可用?自我保护机制是怎么回事?
- 8年软件测试工程师感悟 —— 写给还在迷茫中的朋友
- Kubernetes 进阶训练营 控制器
- 商业智能BI业务分析思维:供应链分析 - 什么是牛鞭效应(一)
- 27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法
猜你喜欢

提速!进口婴幼儿配方产品出证仅需1-3天

商业智能BI业务分析思维:供应链分析 - 什么是牛鞭效应(一)

VIM实用指南(0)基本概念与初次体验

美国弗吉尼亚大学、微软 | Active Data Pattern Extraction Attacks on Generative Language Models(对生成语言模型的主动数据模式提取攻击)

布隆过滤器bloom

Spark: Cluster Computing with Working Sets
MySQL INTERVAL 关键字指南

七夕专属博文-使用QGraphics画“红心“或“黑心“(含数学模型讲解)

Arduino无线下载 Arduino USB接口无线自动下载程序

HashCode technology insider interview must ask
随机推荐
lombok builder重写
pynlpir更新license Error: unable to fetch newest license解决方案
信息录入率百分百上海强化施工现场建筑工人实名制管理
gconf/dconf编程实战(1)gconf和dconf介绍
js邯郸市地图网页源码下载
2022年7月最热的10篇AI论文
VIM实用指南(0)基本概念与初次体验
CodeForces 570D Tree Requests
30分钟成为Contributor|如何多方位参与OpenHarmony开源贡献?
untiy Resorces目录动态加载资源
mysql源码分析——聚簇索引
产品力无提升的雷克萨斯新款ES ,为何敢于涨价?
行程排序(暑假每日一题 12)
【无标题】
主流定时任务解决方案全横评
2022-08-01日报:18张图,直观理解神经网络、流形和拓扑
兆骑科创平台招才引智,海内外高层次人才引进平台
在网站页脚增加几只戏水的小鱼
VIM使用指南(7)单词移动/删除技巧
珠海市生物安全P3实验室主体结构封顶