当前位置:网站首页>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
边栏推荐
猜你喜欢
A full review of mainstream timed task solutions
百图生科卓越开发者计划全面升级暨《计算免疫问题白皮书》发布
canvas粒子雨动画js特效
Shell basic function writing
Arduino无线下载 Arduino USB接口无线自动下载程序
LeetCode50天刷题计划(Day 9—— 整数转罗马数字(20.40-22.10)
MySQL data processing of authorization 】 【
如何有效地开发 Jmix 扩展组件
南京科技大学、中国电子科技第28研究所等联合|MLRIP: Pre-training a military language representation model with informative factual knowledge and professional knowledge base(预训练具有丰富事实知识和专业知识库的军事语言表示模型)
计算机系统与网络安全技术——第一章——信息安全概述——1.1-网络安全定义——什么是信息?
随机推荐
Go 单元测试
打破文件锁限制,以存储力量助力企业增长新动力
行程排序(暑假每日一题 12)
RepOptimizer学习笔记
IronOS, an open source system for portable soldering irons, supports a variety of portable DC, QC, PD powered soldering irons, and supports all standard functions of smart soldering irons
【无标题】
预定义和自定义
接口测试框架开发实践5:配置文件读取
bug- 切换代理服务器与同步 bug
南京科技大学、中国电子科技第28研究所等联合|MLRIP: Pre-training a military language representation model with informative factual knowledge and professional knowledge base(预训练具有丰富事实知识和专业知识库的军事语言表示模型)
兆骑科创科创赛事平台,创业赛事活动路演,线上直播路演
MySQL可以做多台vps的双向同步吗?
未来小间距竞争的着力点在哪里
Can MySQL do two-way synchronization of multiple vps?
给网站增加离开页面改变网站标题效果
Stored procedures in MySQL (detailed)
uwsgi配置文件启动
指针进阶(三)之指针与数组笔试题
MySQL【创建和管理表】
Timezone setting in MySQL