端到端测试(e2e)手册:准备工作:组装 go 语言、工具箱、http 测试服务器。撰写 e2e 检测:应用模拟服务器与应用程序互动,认证回应。运作 e2e 检测:应用 go 的 testing 包运行测试。实战案例 :认证 rest api 的创建记录功能,保证 api 的准确性。e2e 检测针对保证应用软件在真实环境里正常运转尤为重要,文中手册提供了一个循序渐进步骤,以帮助你撰写和运行 e2e 检测,提高应用程序的信心。
Go 框架中的端到端测试手册
端到端测试(E2E)在 Go 框架开发中非常重要,它能确保我们的应用程序在真实环境里正常运转。本文将提供一个循序渐进手册,介绍怎样在 Go 框架中撰写和运行 E2E 检测。
准备工作在进行撰写 E2E 检测以前,大家要准备下列部件:
组装 Go 语言和必要的工具包安装一个 Go 架构,如 Gin、Echo 或 Iris设定 HTTP 测试服务器为了让 E2E 测试与大家的应用程序互动,大家需要设置一个 HTTP 测试服务器。可以用 Go 的 net/http/httptest 包创建一个模拟服务器:
import(
"net/http"
"net/http/httptest"
)
funcNewMockServer()httptest.Server{
mux:=http.NewServeMux()
mux.HandleFunc("/",func(whttp.ResponseWriter,rhttp.Request){
w.Write([]byte("HelloWorld!"))
})
returnhttptest.NewServer(mux)
}
撰写 E2E 检测现在能逐渐撰写 E2E 测试了。使我们创建一个 Gin架构应用软件并撰写一个检测来检验首页回应:
import(
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
funcTestHomepage(ttesting.T){
w:=httptest.NewRecorder()
r:=gin.Default()
r.GET("/",func(cgin.Context){
c.String(http.StatusOK,"HelloWorld!")
})
req,_:=http.NewRequest("GET","/",nil)
r.ServeHTTP(w,req)
ifw.Code!=http.StatusOK{
t.Errorf("Expectedstatuscode%d,got%d",http.StatusOK,w.Code)
}
ifw.Body.String()!="HelloWorld!"{
t.Errorf("Expectedbody%s,got%s","HelloWorld!",w.Body.String())
}
}
运作 E2E 检测应用 Go 的 testing 包运作 E2E 检测:
funcTestMain(mtesting.M){
gofunc(){
svr:=NewMockServer()
defersvr.Close()
}()
os.Exit(m.Run())
}
实战案例 使我们考虑那样一个场景:我们有一个 REST API,接纳 JSON 要求并返回回应。我们能撰写一个 E2E 检测来检验 API 在创建新纪录时的行为:
import(
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
funcTestCreateRecord(ttesting.T){
body,_:=json.Marshal(map[string]string{"name":"JohnDoe"})
req:=http.NewRequest("POST","/api/records",bytes.NewReader(body))
client:=&http.Client{}
resp,err:=client.Do(req)
iferr!=nil{
t.Errorf("Errormakingrequest:%v",err)
}
actual,err:=ioutil.ReadAll(resp.Body)
iferr!=nil{
t.Errorf("Errorreadingresponsebody:%v",err)
}
expected:=`{"id":1,"name":"JohnDoe"}`
assert.JSONEq(t,expected,string(actual))
}
汇总E2E检测针对保证应用程序的准确性尤为重要。文中提供的手册将帮助你入门 Go 框架中的 E2E 检测,并提供了一个实战案例 来检验建立 API 纪录。根据遵照这些步骤,你能撰写健硕且可靠的 E2E 检测,以提高应用程序的信心。
以上就是Go 框架中的端到端测试手册的详细内容,大量请关注其他类似文章!