如何模拟http.NewRequest返回错误

我有一个Go方法,该方法向外部网页发出http请求,即屏幕抓取。 当一切按计划进行时,我都有单元测试。 我可以模拟httpclient并将响应设置为预定义的值。 但是,我在无法正常工作的情况下无法创建测试。 我要模拟http.NewRequest以返回错误。</ p>

我正在使用httptest进行工具覆盖。</ p>

测试方法:</ p >

  func(cli * Client)GetSomething(文本字符串)(字符串,错误){

searchURL:= strings.Replace(someUrl,“ {PERSON_NAME}”,url.QueryEscape (sometext),1)
req,err:= http.NewRequest(“ GET”,someUrl,nil)
if err!= nil {
//我要测试这种情况
返回“”,错误 .Wrap(err,“无法建立请求”)
}

分别,err:= cli.HTTPClient.Do(req)

如果err!= nil {
返回“”,错误。 Wrap(err,“ request failed”)
}

推迟resp.Body.Close()

文档,err:= goquery.NewDocumentFromReader(resp.Body)

如果err!= nil {
return“”,err
}

value:= document.Find(“。someclass”)。Text()

返回值,nil
}
</ code> </ pre>

测试方法适用于httpclient。 不知道如何模拟http.NewRequest以返回错误。 </ p>

  func TestGetSomethingFailedReqest(t * testing.T){

h:= http.HandlerFunc( func(w http.ResponseWriter,r * http.Request){
panic(“创建错误”)
})

// TestingHTTPClient是用于创建HTTPClient的辅助函数。 此测试不需要。

httpClient,拆解:= test.TestingHTTPClient(h)
推迟拆解()
scraperClient:= NewClient()
scraperClient.HTTPClient = httpClient

var person =“ John Doe“

_,错误:= scraperClient.GetSomething(person)

assert.Regexp(t,”。*未能建立请求“,err.Error())
}

</ code> </ pre>
</ div>

展开原文

原文

I have a Go method that makes an http request to an external web page, that I am screen scraping. I have unit tests for when everything works as planned. I can mock the httpclient and set the response to a predefined value. However, I am having trouble creating tests for when things don't work. I want to mock http.NewRequest to return an error.

I am using httptest and go tool cover.

Method to test:

func (cli *Client) GetSomething(sometext string) (string, error) {

    searchURL := strings.Replace(someUrl, "{PERSON_NAME}", url.QueryEscape(sometext), 1)
    req, err := http.NewRequest("GET", someUrl, nil)
    if err != nil {
    // I want to test this scenario
        return "", errors.Wrap(err, "failed to build request")
    }

    resp, err := cli.HTTPClient.Do(req)

    if err != nil {
        return "", errors.Wrap(err, "request failed")
    }

    defer resp.Body.Close()

    document, err := goquery.NewDocumentFromReader(resp.Body)

    if err != nil {
        return "", err
    }

    value:= document.Find(".someclass").Text()

    return value, nil
}

Test Method works for the httpclient. Not sure how to mock http.NewRequest to return an error. This would probably never happen, but just to be complete and as an exercise.

func TestGetSomethingFailedReqest(t *testing.T) {

    h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        panic("Create error")
    })

//TestingHTTPClient is a helper function to create an HTTPClient.  Not needed for this test.

    httpClient, teardown := test.TestingHTTPClient(h)  
    defer teardown()
    scraperClient := NewClient()
    scraperClient.HTTPClient = httpClient

    var person= "John Doe"

    _, err := scraperClient.GetSomething(person)

    assert.Regexp(t, ".*failed to build request", err.Error())
}

douhuan1905
douhuan1905 是的。NewRequest失败的唯一方法几乎是,如果您传递了无效的URL或“无效”(不仅为空,还将默认为GET)方法。后者是一个完全独立的问题,因为根据规范,允许使用非标准方法。
10 个月之前 回复
dragon4587
dragon4587 格式错误的URL应该产生错误,或者URL的格式不是http或https。
10 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问