我在一個(gè)函數(shù)中設(shè)置了一個(gè)大猩猩多路復(fù)用路由器,該函數(shù)返回,如下所示*mux.Routerfunc MakeApp(services service.Service, pe PolicyEnforce) *mux.Router { app := mux.NewRouter() app.NotFoundHandler = &NotFound{} app.Use(token.TokenMiddleware) # ... app.Methods(http.MethodPost).Path("/api/v1/subscription/{emisor}/mh").HandlerFunc(MakeUpdateMH(services, pe)) app.Methods(http.MethodGet).Path("/api/v1/subscription/{emisor}/mh").HandlerFunc(MakeGetMH(services, pe)) app.Methods(http.MethodPost).Path("/api/v1/subscription").HandlerFunc(MakeCreateSubscription(services, pe)) app.Methods(http.MethodGet).Path("/api/v1/subscription/{emisor}").HandlerFunc(MakeGetSubscription(services, pe)) # ... return app}因此,在我的測(cè)試中,我準(zhǔn)備了帶有URL的句柄并運(yùn)行它:func (suite *AppTestSuite) TestUpdateMH() { args := &service.UpdateMHInput{ Usuario: new(string), Clave: new(string), Pin: new(string), Certificado: new(string), Actividades: []string{}, } reader, err := makeBody(args) suite.NoError(err) handle := token.TokenMiddleware(transport.MakeUpdateMH(suite._s, suite.pe)) req := httptest.NewRequest(http.MethodPut, "/api/v1/subscription/-/mh", reader) w := httptest.NewRecorder() t := genToken([]v43.Rol{ { Nombre: "mh", Permisos: []v43.Permiso{{ Sujeto: permission.MHCredentials, Accion: permission.Update, }}, }, }) req.Header.Add("Authorization", t) // configura repository suite.r.On("UpdateIssuerMH", emisor, args.Usuario, args.Clave, args.Pin, args.Certificado, args.Actividades).Return(v43.Grupo{}, nil) handle.ServeHTTP(w, req) resp := w.Result() suite.Equal(http.StatusOK, resp.StatusCode, resp.Status)}我注意到返回而不是值映射,它應(yīng)該包含并且我無法理解為什么情況并非如此。mux.Vars(r)nil{"emisor": "-"}我已經(jīng)在處理何時(shí)為空的情況,但是對(duì)于無法使用“-”或空字符串的其他路由器,此怪癖會(huì)給我?guī)砺闊?,我做錯(cuò)了什么,我如何仍然可以成功運(yùn)行測(cè)試而不必手動(dòng)注入我的Vars?以及:這個(gè)問題會(huì)轉(zhuǎn)化為生產(chǎn)環(huán)境嗎?"emisor"
2 回答

慕姐8265434
TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
如果您正在創(chuàng)建一個(gè)未路由的請(qǐng)求,但您仍然需要 Vars,則還有另一種選擇。
router := mux.NewRouter()
... // setup your routes
var match mux.RouteMatch
success := router.Match(req, &match)
if success {
id := match.Vars["id"]
...
}
這等效于它如何準(zhǔn)備變量,只是它實(shí)際上并不執(zhí)行處理程序。該對(duì)象還包含有關(guān)請(qǐng)求將命中的路由的詳細(xì)信息。router.ServeHTTP(req, res)match

寶慕林4294392
TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
我的設(shè)置是錯(cuò)誤的,我沒有在我的測(cè)試中使用,而是直接調(diào)用處理程序。如果我想使用由我的函數(shù)返回的,那么我需要使用.*mux.Router
*mux.Router
MakeApp
net/http/httptest
- 2 回答
- 0 關(guān)注
- 105 瀏覽
添加回答
舉報(bào)
0/150
提交
取消