【问题标题】:Golang: Testing API using httptest returns 404Golang:使用 httptest 测试 API 返回 404
【发布时间】:2015-03-02 04:05:20
【问题描述】:

我正在尝试测试我编写的与外部 API 对话的库。我想出了这段代码:

import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "net/url"
    "testing"
)

var (
    // mux is the HTTP request multiplexer used with the test server.
    mux *http.ServeMux

    // client is the GitHub client being tested.
    client *Client

    // server is a test HTTP server used to provide mock API responses.
    server *httptest.Server
)

func setup() {
    mux = http.NewServeMux()
    server = httptest.NewServer(mux)

    client = NewClient(nil, "foo")
    url, _ := url.Parse(server.URL)
    client.BaseURL = url

}

func teardown() {
    server.Close()
}

func testMethod(t *testing.T, r *http.Request, want string) {
    if got := r.Method; got != want {
        t.Errorf("Request method: %v, want %v", got, want)
    }
}

func TestSearchForInterest(t *testing.T) {
    setup()
    defer teardown()

    mux.HandleFunc("/topic/search?search-query=Clojure", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, `{"results": [ {"topic": "Clojure", "id": 1000} ]}`)
    })

    results, _, err := client.Topics.SearchForInterest("Clojure")
    if err != nil {
        t.Errorf("SearchForInterest returned error: %v", err)
    }

    fmt.Println(results)

}

当我运行“go test”时,我不断收到错误 404,不确定我做错了什么。任何指针

【问题讨论】:

  • 我从未尝试在路由中包含查询字符串,但这将是我认为“高度可疑”的第一件事
  • 我假设您正在尝试测试:github.com/johnwesonga/go-prismatic?我会尝试验证测试问题,但是您有一些与基于 Master HEAD 的 topic_tagurl 相关的编译器错误。
  • 您创建的路由器没有为“/topic/search?search-query=Clojure”定义路由,那么除了 404 之外,您为什么会期望其他任何东西?
  • sberry - 修复了 tagurl 中的错误,感谢您指出。
  • sberry - 是的,查询字符串是问题..感谢提示:-)

标签: go http-status-code-404


【解决方案1】:

删除查询参数。那不是一条路线。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-29
    • 2015-06-15
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2013-04-15
    相关资源
    最近更新 更多