首页 > 解决方案 > 使用 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

我正在尝试使用 Example 方法编写测试。我创建了一个带有标头(Content-Type:application/json)、查询参数 t=1、方法类型 POST 和 URL localhost 的 http 请求。

got: 和 want: 中的输出看起来是一样的,还检查了空格字符。无法弄清楚这两者之间有什么区别。

无法弄清楚我在这里错过了什么。

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

}

标签: go

解决方案


我认为发生的事情是 HTTP 标头\r\n 的 line break。所以这就是httputil.DumpRequest返回。但是您可能在不\r\n用于换行符的机器上编辑此文件,因此差异来自那里。

成功比较的蛮力方法是:

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

这会从 HTTP 转储的字符串中删除“\r”,如果您的编辑器仅使用“\n”来破坏预期的输出,它将成功比较。

更优雅的解决方案将取决于您的测试环境的具体情况。


推荐阅读