1、所有的单元测试应该从 github 框架源码找答案
2、从goframe的github源码之中拆出一部分验证一下
3、github 库之中的单元测试样例 https://github.com/gogf/gf/blob/master/net/ghttp/ghttp_z_unit_feature_request_test.go
示例代码:
a、控制器
package controller import ( "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" ) // 注册server func SetUpServer() { s := g.Server() s.BindHandler("/get", GetHandle) } // 服务运行 func Run() { g.Server().Run() } // GetHandle 控制器 func GetHandle(r *ghttp.Request) { j, err := r.GetJson() if err != nil { r.Response.Write(err) return } r.Response.Write(j.Get("name")) }
b、测试控制器
package controller import ( "context" "fmt" "testing" "time" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/test/gtest" "github.com/stretchr/testify/assert" ) var ctx = context.TODO() // Test_GetHandle 测试控制器 - 较为麻烦需要手动写web服务运行的命令 // go.exe test -timeout 30s -run ^Test_GetHandle$ example.com/controller func Test_GetHandle(t *testing.T) { g.Server().Start() defer g.Server().Shutdown() SetUpServer() time.Sleep(100 * time.Millisecond) gtest.C(t, func(t *gtest.T) { client := g.Client() client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", g.Server().GetListenedPort())) responseString := client.PostContent(ctx, "/get", `{"id":1, "name":"john"}`) t.Log(responseString) assert.Equal(t, "john", responseString) }) }
当然有时候是希望和 postman 一样验证一下外部接口的可用性,其实就是当成 postman 用了,也没有代码覆盖率
package foo import ( "bytes" "encoding/json" "io/ioutil" "net/http" "testing" "github.com/stretchr/testify/assert" ) // RequestParams API请求参数 type RequestParams struct { Name string `json:"name"` } func GetResultByAPI() string { p := &RequestParams{Name: "jack"} b, _ := json.Marshal(p) resp, err := http.Post( "http://localhost:8080/get", "application/json", bytes.NewBuffer(b), ) if err != nil { return err.Error() } body, _ := ioutil.ReadAll(resp.Body) return string(body) } func TestGetAPI(t *testing.T) { r := GetResultByAPI() assert.Equal(t, "jack", r) }
但是规范开发还是非常有效的,并且自测接口也简单