对 http 请求拦截器进行单元测试

时间:2021-04-06 21:33:48

标签: unit-testing go testify

我对 Go 很陌生,我需要为拦截 http 请求的函数编写一个单元测试,如下所示:

func (sv *Service) SomeMethod(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var ctx = r.Context()
        var uri = r.RequestURI
        ....
        ....
        ....        
    })
}

我不知道如何编写单元测试,调用它并将 httprequest 传递给它,以便执行上面 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 中的所有代码

根据我的测试,

tests := []struct {
        name   string
        args   args
        ..

    }{
        {
            name: "testname",
            args: args{r: &http.Request{Method: "GET", RequestURI: requestUri}},
        },
    }

 for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            // how to invoke the function above???
 
  })
 }

如上面测试下的评论所述,我如何调用该函数(通过 httprequest 等)并对该拦截器进行单元测试?

0 个答案:

没有答案