簡體   English   中英

Golang:使用httptest測試API返回404

[英]Golang: Testing API using httptest returns 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,不確定我在做什么錯。 任何指針

刪除查詢參數。 那不是一條路線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM