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

标签 rest unit-testing go

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"]

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

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

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

下面是我的测试用例的代码。

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)
            }
        }
    })
}

}

最佳答案

最后与

进行了一些讨论之后

mkopriva

我能够解决问题。

我一直在 GetErrResponseList 里面使用 Defer c.Request.Body.Close()

func TheFunc(c *gin.Context) { 

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

}

像这样

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, 
}) 
}

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

关于rest - 通过测试用例,同时给出 500 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52517842/

相关文章:

尝试从 API 获取 JSON 时,Java Spring 出现错误 404。从事 postman 工作

c# - 单元测试 VSTO 项目

unit-testing - 在作为 Prop 传递的函数上调用 Jest spyOn

go - 使用扫描仪时如何获取包括换行符在内的行长?

go - 为什么并行化会减慢我的程序速度?

go - 如何让gocolly爬得更慢

web-services - 如何在 fiddler 中编写对 REST Web 方法的请求

rest - 从网站调用不安全的端点在 HTTPS 下运行 - nginx

java - 命名空间(和操作)应该以斜杠开头吗?

java - 验证方法调用而不在 Spy 上执行其实际实现