httptest.ResponseRecorder没有Result字段或方法。

huangapple go评论172阅读模式
英文:

httptest.ResponseRecorder has no field or method Result

问题

这个问题有点奇怪,我正在尝试获取一个渲染JSON的模拟响应。我的测试代码如下:

import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "reflect"
    "strings"
    "testing"
)
...

func TestMessageFromResponse(t *testing.T) {
    mc := MyController{}
    body := "{ \"message\":\"kthxbai\" }"
    w := httptest.NewRecorder()
    w.Write([]byte(body))
    resp := w.Result()
    msg := mc.messageFromResponse(resp)
    if msg != "kthxbai" {
        t.Errorf("Expected response body to be kthxbai but was %s", msg)
    }
}

我正在测试MyController上的messageFromResponse方法,但它甚至无法构建。当我在项目目录中运行go test时,我收到以下错误信息:

./my_controller_test.go:115: w.Result undefined (type *httptest.ResponseRecorder has no field or method Result)

我还应该提到,在同一个文件中,我成功地将httptest.ResponseRecorder用作另一个地方的写入存根,但是当我尝试访问Result()时,它就会失败。

英文:

So this one is really weird, I'm trying to get a mock response that renders JSON. My test looks like this:

import (
   	"fmt"
   	"net/http"
   	"net/http/httptest"
   	"reflect"
   	"strings"
   	"testing"
)
...
  
func TestMessageFromResponse(t *testing.T) {
   	mc := MyController{}
   	body := "{ \"message\":\"kthxbai\" }"
   	w := httptest.NewRecorder()
   	w.Write([]byte(body))
   	resp := w.Result()
   	msg := mc.messageFromResponse(resp)
   	if msg != "kthxbai" {
   		t.Errorf("Expected response body to be kthxbai but was %s", msg)
   	}
}

I'm testing the method messageFromResponse on MyControllerbut its not even building. When I run go test in my project directory, I get the following error:

./my_controller_test.go:115: w.Result undefined (type *httptest.ResponseRecorder has no field or method Result)

I should also mention that I am successfully using httptest.ResponseRecorder as a writer stub elsewhere in this same file, but it's just failing when I try to access Result().

答案1

得分: 2

我最初将此作为评论进行处理,因为我不确定其相关性,但为了记录:

在线的 godoc 总是引用最新的发布版本。在这种情况下,Result() 方法是在上周发布的 Go1.7 中添加的。如果有疑问,请通过运行 godoc -servergodoc <packagename> 来检查您本地的 godoc。

英文:

I initially addressed this as a comment because I was unsure of relevance, but for posterity:

The online godoc always references the latest release. In this case, the Result() method was added in Go1.7 which only released last week. When in doubt, check your local godoc by running godoc -server or godoc &lt;packagename&gt;.

huangapple
  • 本文由 发表于 2016年8月24日 08:09:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/39112511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定