英文:
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 MyController
but 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 -server
或 godoc <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 <packagename>
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论