当前位置:网站首页>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
边栏推荐
- 使用Canvas实现网页鼠标签名效果
- 【repo】SyntaxError: invalid syntax
- SQL query data and sorting
- 给网站增加离开页面改变网站标题效果
- SyntaxHighlighter带来的字符转义问题
- Spark: Cluster Computing with Working Sets
- Stock Strategy 02 | Technology Timing + Industry Factors + Market Value Rotation
- CodeForces 570D Tree Requests
- 面试必问的HashCode技术内幕
- MySQL可以做多台vps的双向同步吗?
猜你喜欢

Slider/Carousel图片切换支持触摸屏

uniapp 获取cookie与携带cookie请求数据

布隆过滤器bloom

LeetCode50天刷题计划(Day 7—— 字符串转换整数 (atoi) 12.20-15.20)

使用Canvas 实现手机端签名

MySQL【数据处理的增删改】

BPM是什么意思?BPM的优势及好处有哪些?

Timezone setting in MySQL

LeetCode50天刷题计划(Day 9—— 整数转罗马数字(20.40-22.10)

Break the limit of file locks and use storage power to help enterprises grow new momentum
随机推荐
【无标题】
Chapter 13 Manually create a REST service (1)
MySQL查询上的问题
网站2D看板娘收集的可用的模型
VIM实用指南(0)基本概念与初次体验
使用Canvas 实现手机端签名
MySQL [create and manage tables]
会议OA项目(六)--- (待开会议、历史会议、所有会议)
String comparison size in MySQL (date string comparison problem)
强网杯2022 pwn 赛题解析——yakagame
Ranking of itineraries (summer vacation daily question 12)
Spark: Cluster Computing with Working Sets
重庆银河证券股票开户安全吗,是正规的证券公司吗
1个月写900多条用例,2线城市年薪33W+的测试经理能有多卷?
计算机系统与网络安全技术——第一章——信息安全概述——1.1-网络安全定义——什么是信息?
指针进阶(三)之指针与数组笔试题
Convert tensor to image in pytorch
时序数据库在船舶风险管理领域的应用
kubelet node pressure eviction
LeetCode50天刷题计划(Day 8—— 盛最多水的容器(23.00-1.20)