Golang:使用httptest测试API返回404

时间:2015-03-01 19:04:30

标签: go http-status-code-404

我正在尝试测试我编写的与外部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 ,不确定我做错了什么。任何指针

1 个答案:

答案 0 :(得分:1)

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