- 我們前幾天,有寫一個 Go web,那我們現在幫他改一下架構,順便幫他撰寫測試
- 先幫 Controller,更改一下架構,輸出 message
HomeController.go
package controller
import (
"net/http"
"github.com/gin-gonic/gin"
)
func HomepageHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Hi, Iron Man"})
}
main.go
- 接著,因為 controller 有對 function 做更改,所以 main import 也要更改
package main
import (
"github.com/gin-gonic/gin"
"github.com/kevinjone25/go_web/controller"
)
func main() {
server := gin.Default()
server.LoadHTMLGlob("template/*")
server.GET("/home", controller.HomepageHandler)
server.Run()
}
main_test.go
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/kevinjone25/go_web/controller"
"github.com/magiconair/properties/assert"
)
func SetUpRouter() *gin.Engine {
router := gin.Default()
return router
}
func TestHomepageHandler(t *testing.T) {
mockResponse := `{"message":"Hi, Iron Man"}`
r := SetUpRouter()
r.GET("/home", controller.HomepageHandler)
req, _ := http.NewRequest("GET", "/home", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
responseData, _ := ioutil.ReadAll(w.Body)
assert.Equal(t, mockResponse, string(responseData))
assert.Equal(t, http.StatusOK, w.Code)
}
- 首先,設定 mockMessage,這個值是我們預計會拿到的值
- 接著透過
w
來記錄 request 的值
- 用 HomeHandler 來啟動 ServeHttp
- 接著下面的
assert.Equal
是用來測試回傳值是否相等,包括回傳的 status Code & response data等
go test
- 接著透過以下指令來把 Unit testing 跑起來
go test
![](https://i.imgur.com/ifcKVKo.png)