Go Fiber 框架系列教程 04:測試應用
閱讀本文大概需要 5 分鐘。
大家好,我是 polarisxu。
實際項目中,大家經(jīng)常不會對 Web API 寫單元測試。Go 標準庫不僅有 testing 包支持普通單元測試,還有 net/http/httptest 包支持 HTTP 的測試。
本文雖然是測試 Fiber 應用程序,但對其他的框架也適用。
01 如何測試
Web API 的單元測試如何進行?
本節(jié)介紹的測試方法主要是驗證請求返回的 HTTP 狀態(tài)碼是否符合預期。
如果返回的狀態(tài)碼是 200 OK,那么表示這個測試用例成功(Pass),如果返回的狀態(tài)碼是 404 Not Found,那么表示這個測試用例失?。‵ail)。所以,要求請求返回正確的狀態(tài)碼。
02 VSCode 生成測試
VSCode 安裝了 Go Team 的 Go 插件后,可以一鍵生成單元測試。
在某個函數(shù)上右鍵,出現(xiàn)的菜單中會有 Generate Unit Tests For Function:

點擊它會自動創(chuàng)建 main_test.go 文件,并生成類似下面的代碼:
package?main
import?"testing"
func?Test_main(t?*testing.T)?{
?tests?:=?[]struct?{
??name?string
?}{
??//?TODO:?Add?test?cases.
?}
?for?_,?tt?:=?range?tests?{
??t.Run(tt.name,?func(t?*testing.T)?{
???main()
??})
?}
}
03 動手寫單元測試
動手之前,需要先介紹下 Fiber 中專門針對測試提供的方法:
//?Test?is?used?for?internal?debugging?by?passing?a?*http.Request.
//?Timeout?is?optional?and?defaults?to?1s,?-1?will?disable?it?completely.
func?(app?*App)?Test(req?*http.Request,?msTimeout?...int)?(resp?*http.Response,?err?error)
該方法接收一個 *http.Request,返回 *http.Response,通過這個 Response 可以獲得 HTTP StatusCode。
待測試的程序如下:
//?main.go
package?main
import?(
?"github.com/gofiber/fiber/v2"
)
func?setupRoutes(app?*fiber.App)?{
?app.Get("/hello",?func(ctx?*fiber.Ctx)?error?{
??return?ctx.SendString("Hello?World!")
?})
}
func?main()?{
?app?:=?fiber.New()
?setupRoutes(app)
?app.Listen(":3000")
}
測試程序如下:
package?main
import?(
?"net/http/httptest"
?"testing"
?"github.com/gofiber/fiber/v2"
?"github.com/stretchr/testify/assert"
)
func?TestHelloRoute(t?*testing.T)?{
?tests?:=?[]struct?{
??description??string
??route????????string?//?route?path?to?test
??expectedCode?int????//?expected?HTTP?status?code
?}{
??{
???description:??"get?HTTP?status?200",
???route:????????"/hello",
???expectedCode:?200,
??},
??{
???description:??"get?HTTP?status?404,?when?route?is?not?exists",
???route:????????"/notfound",
???expectedCode:?404,
??},
?}
?app?:=?fiber.New()
?setupRoutes(app)
?for?_,?test?:=?range?tests?{
??//?利用?httptest?包生成?request
??req?:=?httptest.NewRequest("GET",?test.route,?nil)
??resp,?_?:=?app.Test(req,?1)
??assert.Equalf(t,?test.expectedCode,?resp.StatusCode,?test.description)
?}
}
我們還用了 github.com/stretchr/testify 庫,這是一個輔助測試的庫,assert 是它的子包,用于進行斷言。
然后運行如下命令測試:
$?go?test?-v?.
===?RUN???TestHelloRoute
---?PASS:?TestHelloRoute?(0.00s)
PASS
ok???github.com/polaris1119/fiber-example
04 總結
本文從 HTTP 狀態(tài)碼的維度測試 Web API,保證 API 大的邏輯正確,但不包括業(yè)務邏輯相關的測試。
我是 polarisxu,北大碩士畢業(yè),曾在 360 等知名互聯(lián)網(wǎng)公司工作,10多年技術研發(fā)與架構經(jīng)驗!2012 年接觸 Go 語言并創(chuàng)建了 Go 語言中文網(wǎng)!著有《Go語言編程之旅》、開源圖書《Go語言標準庫》等。
堅持輸出技術(包括 Go、Rust 等技術)、職場心得和創(chuàng)業(yè)感悟!歡迎關注「polarisxu」一起成長!也歡迎加我微信好友交流:gopherstudio
