Rest 通过测试用例,同时给出500作为响应

Rest 通过测试用例,同时给出500作为响应,rest,unit-testing,go,Rest,Unit Testing,Go,我有一个TestFunction,在其中我使用了这段代码。这是密码 测试RESTAPI的GET请求 在我的第一个测试用例中,我命中了一个已定义的处理程序,而在第二个测试用例中,我命中了一些随机处理程序,以便使该用例失败 代码正在通过,但每次第二个测试用例都给出500作为响应 下面是我的测试用例代码 request, err := http.NewRequest("GET", path, nil) response := httptest.NewRecorder() r.ServeHTTP(res

我有一个TestFunction,在其中我使用了这段代码。这是密码 测试RESTAPI的GET请求

在我的第一个测试用例中,我命中了一个已定义的处理程序,而在第二个测试用例中,我命中了一些随机处理程序,以便使该用例失败

代码正在通过,但每次第二个测试用例都给出500作为响应

下面是我的测试用例代码

request, err := http.NewRequest("GET", path, nil)
response := httptest.NewRecorder()
r.ServeHTTP(response, request)
var raw map[string]map[string]string
_ = json.Unmarshal(response.Body.Bytes(), &raw)
details := raw["response"]

}

最后,在与

姆科普里瓦

我能解决这个问题

我一直在使用GetErrResponseList中的Defer c.Request.Body.Close

func TestGetProviders(t *testing.T) {
type args struct {
    path    string
    handler gin.HandlerFunc
}
tests := []struct {
    name string
    args args
    want bool
}{
    {
        "First",
        args{
            "/api/v1/providers",
            GetProviders,
        },
        true,
    },
    {
        "Second",
        args{
            "/demo",
            TheFunc,
        },
        false,
    },
}
for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        value := copyCodeGet(tt.args.path, tt.args.handler)
        if len(value["response"]) > 0 {
            statusCode, _ := strconv.Atoi(value["response"]["code"])
            if val := statusCode == config.SuccessCode && value["response"]["message"] == config.SuccessMsg; val != tt.want {
                t.Errorf("Error is:%v && Status code should be %v, was %d.", value, http.StatusOK, statusCode)
            }
        }
    })
}
像这样

func TheFunc(c *gin.Context) { 

GetErrResponseList(c, config.FailureMsg, nil, nil) 

}

这导致了问题,因为不需要在处理程序中关闭请求主体。因此,它在可以使用之前关闭了主体,因此将其移除就解决了问题。

您能否显示出无法正常工作的代码?基金会?。。。另外,不要忽略json.Unmarshal中的错误,它可能会指向您的bug.func TheFuncc*gin.Context{GetErrResponseListc,config.FailureMsg,nil,nil}这只是一个简单的函数,它将给出400作为响应代码。。。假设TestGetProviders被集成到测试GetProviders中,那么第二个测试用例就没有意义了,因为它根本不测试该处理程序,它使用不同的端点执行不同的处理程序,您从该测试用例中得不到关于GetProviders的任何知识。但它不应该给出500作为错误
func GetErrResponseList(c *gin.Context, msg string, data, count interface{}) { 
defer c.Request.Body.Close() 
response := ResponseControllerList{400, 0, msg, data, count} 
c.JSON(200, gin.H{ 
config.Response: response, 
}) 
}