I was wondering what is the cleanest way to set url params when we test handlers, and thought it might be useful to make xmux.newParamContext public, or create another xmux.TestNewParamContext just for testing. I'll describe the concrete example below, and would appreciate if you can give me some feedback.
Suppose we have the following handler and server.
func helloWithParam(ctx context.Context, w http.ResponseWriter, r *http.Request) {
n := xmux.Param(ctx, "name")
fmt.Fprintf(w, "Hello, %s!", n)
return
}
func main() {
m := xmux.New()
m.GET("/hello/:name", xhandler.HandlerFuncC(helloWithParam))
if err := http.ListenAndServe(":8888", xhandler.New(context.Background(), m)); err != nil {
log.Fatal(err)
}
}
I want to test like the below so that I can test only a simple function, keeping routing/middleware aside.
func TestHelloWithParam(t *testing.T) {
n := "dummyName"
ps := xmux.ParamHolder{xmux.Parameter{Name: "name", Value: n}}
ctx := xmux.NewParamContext(context.TODO(), ps) // This line could be xmux.TestNewParamContext()
req, _ := http.NewRequest("GET", "/hello/"+n, nil)
w := httptest.NewRecorder()
helloWithParam(ctx, w, req)
t.Log(w.Body)
}
The idea of test helper public API is borrowed from this slide.
I was wondering what is the cleanest way to set url params when we test handlers, and thought it might be useful to make
xmux.newParamContext
public, or create anotherxmux.TestNewParamContext
just for testing. I'll describe the concrete example below, and would appreciate if you can give me some feedback.Suppose we have the following handler and server.
I want to test like the below so that I can test only a simple function, keeping routing/middleware aside.
The idea of test helper public API is borrowed from this slide.