英文:
Golang: Testing API using httptest returns 404
问题
我正在尝试测试我编写的与外部API通信的库。我写了以下代码:
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
var (
// mux是与测试服务器一起使用的HTTP请求多路复用器。
mux *http.ServeMux
// client是正在测试的GitHub客户端。
client *Client
// server是用于提供模拟API响应的测试HTTP服务器。
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,不确定我做错了什么。有什么指导意见吗?
英文:
I'm trying to test a library I wrote that talks to an external API. I came up with this code:
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)
}
When I run "go test" I keep getting an error 404 not sure what I'm doing wrong. any pointers
答案1
得分: 1
删除不是路由的查询参数。
英文:
Remove the query param. that isn't a route.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论