Golang:使用httptest测试API返回404错误。

huangapple go评论93阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年3月2日 03:04:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/28797765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定