Go Testing单元测试

使用Golang编程时,一般只有在写最终的main函数时我们才有机会调用某个函数进行测试,在大型项目中如果只负责编写某个非main模块时应当如何测试函数的可用性?

Golang提供了Testing模块,这个模块可以让我们随时随地进行函数功能验证。

testing - The Go Programming Language (golang.org)

示例:

假设某个名为anytest的Package目录下有如下的正常业务逻辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package anytest
 
import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)
 
type JsonResponse struct {
    ...
}
 
func Call() error{
    resp,_ := http.Get("xxx")
    respBody,_ := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()
    jsonResp := new(JsonResponse)
    if err := json.Unmarshal(respBody, jsonResp); err != nil {
        return err
    }
    fmt.Println(jsonResp.Stores)
    return nil
}

然后我们创建anytest_test.go用于测试包内的某些函数或方法(必须以_test.go结尾,前缀随意彰显目的即可):

1
2
3
4
5
6
7
8
9
10
11
12
package anytest //同一package中
 
import (
    "testing"
)
 
func TestCall(t *testing.T)  { //必须以Test开头,推荐以Test_开头,后缀一般使用被测试的函数名标识
    err := Call()
    if err != nil {
        t.Error(err)    //testing.T自带log类打印方法
    }
}

进行测试:

1
2
3
4
5
6
7
8
9
// 建议在对应package目录下执行对应package的go test
1. 测试本目录下所有test.go文件
go test
 
2. 测试某个test.go文件(注意必须添加./的路径前缀,否则会把文件名当函数名去匹配)
go test -v -run ./my_test.go
 
3. 测试某个Test函数(会遍历package目录下所有test.go文件找到对应的函数)
go test -v -run Test_mytest

 

posted @   realcp1018  阅读(151)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示