initRouter\initRouter.go
package initRouter
import (
"github.com/gin-gonic/gin"
"net/http"
)
func SetupRouter() *gin.Engine {
router := gin.Default()
// 添加 Get 请求路由
router.GET("/", func(context *gin.Context) {
context.String(http.StatusOK, "hello gin")
})
return router
}
main.go:
package main
import (
"GinHello/initRouter"
)
func main() {
router := initRouter.SetupRouter()
_ = router.Run()
}
建? test ?录, golang 的单元测试都是以 _test 结尾,建? index_test.go ?件。
package test
import (
"GinHello/initRouter"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)
func TestIndexGetRouter(t *testing.T) {
router := initRouter.SetupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/", nil)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "hello gin", w.Body.String())
}
通过 assert 进?断?,来判断返回状态码和返回值是否与代码中的值?致。
GinHello
|
|-initRouter
| |-initRouter.go
|
|-test
| |-index_test.go
|
|-main.go
|-go.mod
|-go.sum
运?单元测试,控制台打印出单元测试结果。
— PASS: TestIndexGetRouter (0.05s) PASS