安装第三方包testify来使用高级断言。要做到这一点,请遵循以下步骤:
1、下载testify第三方包:
go get github.com/stretchr/testify
2、更新测试用例TestIndexHandler,使用testify包的assert属性:
func TestIndexHandler(t *testing.T) {
mockUserResp := `{"message":"hello world"}`
ts := httptest.NewServer(SetupServer())
defer ts.Close()
resp, err := http.Get(fmt.Sprintf("%s/", ts.URL))
defer resp.Body.Close()
assert.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
responseData, _ := ioutil.ReadAll(resp.Body)
assert.Equal(t, mockUserResp, string(responseData))
}
为特定Handler写测试用例
假设你的代码里面有自己API路由及其处理程序,如下所示:
func main() {
router := gin.Default()
router.POST("/recipes", NewRecipeHandler)
router.GET("/recipes", ListRecipesHandler)
router.PUT("/recipes/:id", UpdateRecipeHandler)
router.DELETE("/recipes/:id", DeleteRecipeHandler)
router.GET("/recipes/:id", GetRecipeHandler)
router.Run()
}
GET请求处理程序单元测试
下面以ListRecipesHandler处理程序为例写单元测试:
//为测试使用创建 *gin.Engine实例
func SetupRouter() *gin.Engine {
router := gin.Default()
return router
}
func TestListRecipesHandler(t *testing.T) {
r := SetupRouter()
//将项目中的API注册到测试使用的router
r.GET("/recipes", ListRecipesHandler)
//向注册的路有发起请求
req, _ := http.NewRequest("GET", "/recipes", nil)
w := httptest.NewRecorder()
//模拟http服务处理请求
r.ServeHTTP(w, req)
var recipes []Recipe
json.Unmarshal([]byte(w.Body.String()), &recipes)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, 492, len(recipes))
}
POST请求处理程序单元测试
func TestNewRecipeHandler(t *testing.T) {
r := SetupRouter()
r.POST("/recipes", NewRecipeHandler)
//创建post请求体
recipe := Recipe{
Name: "New York Pizza",
}
//序列化请求体
jsonValue, _ := json.Marshal(recipe)
//发起post请求
req, _ := http.NewRequest("POST", "/recipes", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}