-
Notifications
You must be signed in to change notification settings - Fork 1.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to set URL parameters for unit tests? #167
Comments
Note: also discussed in #112 The short answer: using https://golang.org/pkg/net/http/httptest/#Server + setting The long answer: changing the type of |
@elithrar thanks for the reply. I'm not sure to understand your solution. How does the context get populated if the mux isn't involved? Can you please provide more informations or point to an example? |
@bhirbec You populate the context by passing the correct URL - e.g. r := mux.NewRouter()
r.HandleFunc("/hello/{name}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, client")
}))
ts := httptest.NewServer(r)
defer ts.Close()
// Table driven test
names := []string{"kate", "matt", "emma"}
for _, name := range names {
url := ts.URL + "/hello/" + name
resp, err := http.Get(url)
if err != nil {
t.Fatal(err)
}
if status := resp.Code; status != http.StatusOK {
t.Fatalf("wrong status code: got %d want %d", status, http.StatusOK)
}
} This way—regardless of whether you use gorilla/mux or not—you're still testing that your application handles the route variables you're passing. |
Closing this out for now. Re-open if any questions! |
@elithrar For the love of all that is holy, please just expose a |
It would be great help, if you guys export the
|
Any update on this? |
Yep. I have just seen them several hours ago. Thank you! |
Thanks @elithrar ! |
Handy function for testing! |
@palsivertsen Would you like to PR that? :) |
Hi,
I need to set up URL parameters for my unit tests. I'm using context.Set() to do so and my test looks something like this:
The HTTP handler uses mux.Vars() to retrieve the parameters but it doesn't get any. The problem is explained in great details in this post:
I'm aware I could solve my problem by either starting a web server or by calling the mux directly (as mentioned in SO). However, I don't want to do so. I'd like to call the handler directly in my test.
I see two options to solve this:
int
instead ofcontextKey
type when definingvarsKey
. This waycontext.Set(r, 0, map[string]string{"param1": "123"})
would be a valid way to set up URL parameters.Hope this help. Thanks for making Gorilla :)
Ben
The text was updated successfully, but these errors were encountered: