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.

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

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试