duanfei1930 2018-09-26 12:31
浏览 24
已采纳

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

I have a TestFunction in which I am using this code. It is code to test the REST API for a GET request.

In my first test case I hit a defined handler while in the second test case I am hitting some random handler so as to make that case fail.

The code is getting passed but every time the second test case is giving 500 as the response.

Below is the code of my test case.

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

}

  • 写回答

1条回答 默认 最新

  • douxuanma4357 2018-09-26 13:25
    关注

    Finally After Some Discussion with

    mkopriva

    I Was Able To Solve The Problem.

    I have been Using Defer c.Request.Body.Close() in GetErrResponseList inside the

    func TheFunc(c *gin.Context) { 
    
    GetErrResponseList(c, config.FailureMsg, nil, nil) 
    
    }
    

    like this

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

    Which Was Causing The Problem as a request body does not need to be closed in the handler. and so it was closing the body just before it could be used and hence removing it solved the problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?