> For the complete documentation index, see [llms.txt](https://minilabmemo.gitbook.io/golang-memo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://minilabmemo.gitbook.io/golang-memo/advance-application/gin-web-framework/gintest.md).

# GinTest

### ginTest

```go
//go test -v .
func TestInfoHandler(t *testing.T) {
	// main
	gin.SetMode(gin.ReleaseMode)
	engine := gin.New()
	loadRoutes(engine) //設定你寫路由
	//StartHttpServer(errs, engine) // 略 不會真的執行

//--關鍵段落------------
	w := httptest.NewRecorder()                                   // 取得 ResponseRecorder 物件
	req, _ := http.NewRequest("GET", "/service/api/v1/info", nil) //使用 http 建立一個 Request
	engine.ServeHTTP(w, req)                                      //使用 gin 提供的 ServeHTTP 模擬 API 呼叫．response 會放入ResponseRecorder
//--------------
	//驗證發起請求後的回覆是否正確
	assert.Equal(t, http.StatusOK, w.Code)
	t.Log("body", w.Body.String()) //使用go test -v 才可以印出
	expactedResp := `{"name":"rest-demo","version":"1.0.0"}`
	if !reflect.DeepEqual(w.Body.String(), expactedResp) {
		t.Errorf("Resp(%s) != expactedResp(%s)", w.Body.String(), expactedResp)
	}
}


//其中部分關鍵段落可以抽出，下次可以覆用
// 模擬發生
func httpTestGetRequest(url string, engine *gin.Engine) *httptest.ResponseRecorder {
	w := httptest.NewRecorder()                                            // 取得 ResponseRecorder 物件
	req, _ := http.NewRequest(http.MethodGet, "/service/api/v1/info", nil) //使用 http 建立一個 Request
	engine.ServeHTTP(w, req)                                               //使用 gin 提供的 ServeHTTP 模擬 API 呼叫．response 會放入ResponseRecorder
	defer w.Result().Body.Close()
	return w
}
```

| 參考                                                                                                                         |                                                              |
| -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| [\[Go\] Unit testing HTTP servers with Gin](https://mileslin.github.io/2020/06/Golang/Unit-testing-HTTP-servers-with-Gin/) | 要把建立 gin.Engine 與設定路由抽一個方法出來，因為等等寫測試的時候，會需要取得 gin.Engine 物件。 |
| [gin 源码阅读(2) - http请求是如何流入gin的?](https://cloud.tencent.com/developer/article/1885821)                                      | gin.ServeHTTP 的实现                                            |
|                                                                                                                            |                                                              |
