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

如何在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 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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度