duanpu8830 2019-02-15 23:01
浏览 66
已采纳

使用ExampleTest进行测试-预期输出不匹配

Running tool: /usr/local/go/bin/go test -timeout 30s -run ^(ExampleBuild)$

--- FAIL: ExampleBuild (0.00s)
got:
POST localhost/status?t=1 HTTP/1.1
Content-Type: application/json
want:
POST localhost/status?t=1 HTTP/1.1
Content-Type: application/json
FAIL
exit status 1

I'm trying to write test in go using the Example method. I have created a http request with header (Content-Type: application/json), query param t=1, method type POST and URL localhost.

The output in got: and want: looks to be the same, have also checked for whitespace characters. Not able to figure out what is the difference between these two here.

Not able to figure out what am I missing here.

import (
   "fmt"
   "net/http"
   "net/http/httputil"
)

func ExampleBuild() {

    req, err := http.NewRequest(http.MethodPost, "localhost/status?t=1", nil)
    req.Header.Add("content-type", "application/json")
    if err != nil {
        panic(err)
    }

    str, err := httputil.DumpRequest(req, false)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%s", string(str))
    // Output:
    // POST localhost/status?t=1 HTTP/1.1
    // Content-Type: application/json

}
  • 写回答

1条回答 默认 最新

  • dongyou5098 2019-02-15 23:28
    关注

    I think what's happening is that the HTTP header has for its line break. So this is what httputil.DumpRequest returns. But you're probably editing this file on a machine that doesn't use for line breaks, so the difference comes from there.

    A brute-force way to compare successfully would be:

    fmt.Println(strings.Replace(string(str), "", "", -1))
    

    Which removes the ""s from the string dumped by HTTP and it will compare successfully if your editor used only " " to break the expected output.

    A more elegant solution would depend on the specifics of your testing environment(s).

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

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂