Golang:使用httptest测试API返回404
我正在尝试测试我编写的一个与外部API对话的库。我想出了这个密码:Golang:使用httptest测试API返回404,go,http-status-code-404,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
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不确定我做错了什么。任何指针都将删除查询参数。那不是一条路线 我从来没有尝试过在路由中包含查询字符串,但这将是第一件让我感到“高度可疑”的事情,我假设您正在尝试测试:?我会尝试验证测试问题,但您有一些与基于主标题的topic_tagurl相关的编译器错误。您创建的路由器没有为“/topic/search?search query=Clojure”定义路由,所以为什么您希望除了404?sberry之外的任何东西-修复了tagurl中的错误,谢谢你指出。sberry-是的,问题出在查询字符串上。谢谢你的提示:-)