dongtuo1482
2017-07-16 07:53
浏览 80
已采纳

如何在读取请求正文时测试错误?

I'm writing unit tests for http Handlers in golang. When looking at code coverage reports of this I am running into the following issue: When reading the request body from a request, ioutil.ReadAll might return an error that I need to handle. Yet, when I write unit tests for my handler I do not know how to send a request to my handler in a way that it will trigger such an error (premature end of content seems not to generate such an error but will generate an error on unmarshaling the body). This is what I am trying to do:

package demo

import (
    "bytes"
    "io/ioutil"
    "net/http"
    "net/http/httptest"
    "testing"
)

func HandlePostRequest(w http.ResponseWriter, r *http.Request) {
    body, bytesErr := ioutil.ReadAll(r.Body)
    if bytesErr != nil {
        // intricate logic goes here, how can i test it?
        http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
        return
    }
    defer r.Body.Close()
    // continue...
}

func TestHandlePostRequest(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(HandlePostRequest))
    data, _ := ioutil.ReadFile("testdata/fixture.json")
    res, err := http.Post(ts.URL, "application/json", bytes.NewReader(data))
    // continue...
}

How can I write a test case for HandlePostRequest that also covers the case of bytesErr not being nil?

图片转代码服务由CSDN问答提供 功能建议

我正在用golang编写HTTP处理程序的单元测试。 查看此代码的覆盖率报告时,我遇到了以下问题:从请求中读取请求正文时, ioutil.ReadAll 可能会返回我需要处理的错误。 但是,当我为处理程序编写单元测试时,我不知道如何以触发该错误的方式将请求发送到处理程序(内容的过早终止似乎不会生成此类错误,但会在 解开身体)。 这是我要尝试的操作:

 程序包演示
 
import(
“字节” 
“ io / ioutil” 
“ net / http” \  n“ net / http / httptest” 
“测试” 
)
 
func HandlePostRequest(w http.ResponseWriter,r * http.Request){
 body,bytesErr:= ioutil.ReadAll(r.Body)\  n如果bytesErr!= nil {
 //复杂的逻辑在这里,我该如何测试?
 http.Error(w,http.StatusText(http.StatusBadRequest),http.StatusBadRequest)
 return 
} \  n defer r.Body.Close()
 //继续... 
} 
 
func TestHandlePostRequest(t * testing.T){
 ts:= httptest.NewServer(http.HandlerFunc(HandlePostRequest))\  n数据,_:= ioutil.ReadFile(“ testdata / fixture.json”)
 res,错误:= http.Post(ts.URL,“ application / json”,bytes.NewReader(data))
 // 继续... 
} 
   
 
 

我如何为 HandlePostRequest 编写一个测试用例,其中也包括 bytesErr的情况 不是 nil 吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题