当前位置:网站首页>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
边栏推荐
- 80篇国产数据库实操文档汇总(含TiDB、达梦、openGauss等)
- LeetCode50天刷题计划(Day 6—— 整数反转 14.20-15.20)
- 2022-08-01 Daily: 18 graphs to intuitively understand neural networks, manifolds and topology
- MySQL [create and manage tables]
- 在网站页脚增加几只戏水的小鱼
- 数据抽取过滤的时候,数据库字段update_at类型是timestamp,抽取T-1日数据这个变量条
- what is tail tooth feast
- 面试必问的HashCode技术内幕
- kubelet节点压力驱逐
- Could not write header for output file #0 (incorrect codec parameters ?): ……
猜你喜欢

布隆过滤器bloom

通胀持续 肯尼亚粮食安全引关注

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

Stock Strategy 02 | Technology Timing + Industry Factors + Market Value Rotation

Inflation continues, Kenya's food security a concern

Next-ViT学习笔记

RepOptimizer学习笔记

打破文件锁限制,以存储力量助力企业增长新动力

指针进阶(三)之指针与数组笔试题

uwsgi配置文件启动
随机推荐
SQL query data and sorting
输出0-1背包问题的具体方案 ← 利用二维数组
what is tail tooth feast
urlopen error errno111(英雄联盟报错error)
Could not write header for output file #0 (incorrect codec parameters ?): ……
MySQL:索引
MySQL INTERVAL 关键字指南
Convert tensor to image in pytorch
时序数据库在船舶风险管理领域的应用
2022-08-01日报:18张图,直观理解神经网络、流形和拓扑
wordpress模板函数说明备注整理收藏
【无标题】
LeetCode50天刷题计划(Day 9—— 整数转罗马数字(20.40-22.10)
面试必问的HashCode技术内幕
月薪12K,蝶变向新勇往直前,我通过转行软件测试实现月薪翻倍...
Zhaoqi Science and Technology Innovation Event Platform, Entrepreneurship Event Roadshow, Online Live Roadshow
MySQL查询上的问题
BPM是什么意思?BPM的优势及好处有哪些?
flink -redis sink 可以sink 到集群吗?
Spark: Cluster Computing with Working Sets