dongranding3909
dongranding3909
2016-09-23 19:49
浏览 43
已采纳

如何在Go中将json字符串硬编码到* http.Response以进行测试

I have some code that makes get requests to a dynamic website, which I want to test. Obviously the tests need to be run by anyone at any time, so rather than actually use the REST API, is it possible to put a json string into an *http.Response for testing purposes.

example code:

func get (c *http.Response, err error) (string, error) {
    //code
}

test file:

func TestGet(t *testing.T) {
    //code to have put json string for test *http.Response
    get(???, nil)

}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drwurqczo39355510
    drwurqczo39355510 2016-09-23 19:56
    已采纳

    You want to use a bytes.Buffer to turn the data you have into an io.Reader, and NopCloser (from io/ioutil) to make it an io.ReadCloser

    r := &http.Response{
        Status: "200 OK",
        StatusCode: 200,
        // etc., lots more fields needed here.
        Body: ioutil.NopCloser(bytes.NewBufferString(json))
    }
    

    If you have your json in a []byte, then use NewBuffer instead of NewBufferString.

    点赞 评论

相关推荐