Go Testing单元测试

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

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

testing - The Go Programming Language (golang.org)

示例:

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

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结尾,前缀随意彰显目的即可):

package anytest //同一package中

import (
    "testing"
)

func TestCall(t *testing.T)  { //必须以Test开头,推荐以Test_开头,后缀一般使用被测试的函数名标识
    err := Call()
    if err != nil {
        t.Error(err)    //testing.T自带log类打印方法
    }
}

进行测试:

// 建议在对应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 @ 2022-11-25 16:43  realcp1018  阅读(144)  评论(0编辑  收藏  举报