偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《在 go echo 中测试 http 处理程序》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!
问题内容我正在学习 go echo 和单元测试,我陷入了困境,我来这里寻求帮助。
func testgetgameswithtags(t *testing.t){
req := httptest.newrequest("http.methodget", "/games?tags=tag0", nil)
//response writer
// we can inspect the responserecorder output which is response generated by handler
recorder := httptest.newrecorder()
globaltestserver.echo.servehttp(recorder, request)
// i dont know what to do after this
}
我不知道之后该做什么
GlobalTestServer.echo.ServeHTTP(recorder, request)
正确答案
为了测试您的 echo
处理程序,您需要一堆东西,echo context
、request
、recorder
,这是一个示例:
import (
"net/http"
"net/http/httptest"
"net/url"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetGamesWithTags(t *testing.T) {
// Create an instance of Echo.
e := echo.New()
// Create http test recorder
rec := httptest.NewRecorder()
// Add url params
q := make(url.Values)
q.Set("tags", "tag0")
req := httptest.NewRequest(http.MethodGet, "/?"+q.Encode(), nil)
// Create new echo context
c := e.NewContext(req, rec)
// Invoke your handlers against echo context
assert.NoError(t, getGamesWithTags(c))
require.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(
t,
`{"key":"value"}`,
rec.Body.String(),
)
}
以上就是《在 go echo 中测试 http 处理程序》的详细内容,更多关于的资料请关注编程网公众号!