2 回答
TA贡献1887条经验 获得超5个赞
我建议看一下httptest包。它有一个非常适合您的假 HTTP 服务器。
func Test_httpClient(t *testing.T){
var called bool
defer func(){
if !called{
t.Fatal("expected endpoint to be called")
}
}()
expectedValue = "some-value"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
called = true
u,p,ok := r.BasicAuth()
if !ok || u != "fakeuser" || p != "fakepassword" {
t.Fatal("wrong auth")
}
w.Write([]byte(expectedValue))
})
val, err := httpClient(
[]string{"fakeuser", "fakepasswword"},
http.MethodPost,
server.URL,
)
if err != nil{
t.Fatal(err)
}
if val != expectedValue {
t.Fatalf("expected %q to equal %q", val, expectedValue)
}
}
TA贡献1853条经验 获得超6个赞
我会使用类似以下代码的东西。用法是newTestServer(address).run()
import (
"github.com/gorilla/mux"
"net/http"
"sync"
"time"
)
type testServer struct {
addr string
router *mux.Router
}
// addr can be e.g. `localhost:3030`
// -> your client will do request on `localhost:3030/some/endpoint/path`
func newTestServer(addr string) *testServer {
router := mux.NewRouter()
router.HandleFunc(
"/some/endpoint/path",
handleEndpoint,
).Methods(http.MethodPost)
return &testServer{
addr: addr,
router: router,
}
}
func handleEndpoint(writer http.ResponseWriter, request *http.Request) {
// your implementation
}
func (server *testServer) run() {
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
wg.Done()
if err := http.ListenAndServe(server.addr, server.router); err != nil {
panic(err)
}
}()
wg.Wait() // wait for goroutine starts
time.Sleep(100 * time.Millisecond) // wait for listening starts
}
但我认为测试仍然不会通过。
// this will panic
// requires 2nd and 3rd item in an array
req.SetBasicAuth(cc[1], cc[2])
- 2 回答
- 0 关注
- 107 浏览
添加回答
举报