当前位置:网站首页>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
边栏推荐
猜你喜欢

产品力无提升的雷克萨斯新款ES ,为何敢于涨价?

Meeting OA project (6) --- (to-be-opened meeting, historical meeting, all meetings)

如何防止重复下单?

月薪12K,蝶变向新勇往直前,我通过转行软件测试实现月薪翻倍...

Timezone setting in MySQL

canvas粒子雨动画js特效

Inflation continues, Kenya's food security a concern

珠海市生物安全P3实验室主体结构封顶

1个月写900多条用例,2线城市年薪33W+的测试经理能有多卷?

强网杯2022 pwn 赛题解析——yakagame
随机推荐
“查找附近的商铺”|Geohash+MySQL实现地理位置筛选
测试工程师进阶必读书目
面试必问的HashCode技术内幕
Zhaoqi Science and Technology Innovation Platform attracts talents and attracts talents, and attracts high-level talents at home and abroad
Slider/Carousel图片切换支持触摸屏
hzero-resource秒退
27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!
ECCV 2022 | Poseur:你以为我是姿态估计,其实是目标检测哒
pytorch测试的时候为何要加上model.eval()?
flink-sql 可以单独配置某个算子节点的并行度吗?
kubelet节点压力驱逐
wordpress模板函数说明备注整理收藏
Spark: Cluster Computing with Working Sets
南京科技大学、中国电子科技第28研究所等联合|MLRIP: Pre-training a military language representation model with informative factual knowledge and professional knowledge base(预训练具有丰富事实知识和专业知识库的军事语言表示模型)
May 20, 2022 The most complete fish game navigation
mysql源码分析——聚簇索引
Shell basic function writing
MySQL [create and manage tables]
数据抽取过滤的时候,数据库字段update_at类型是timestamp,抽取T-1日数据这个变量条
Kernel pwn 入门 (6)