I am writing the unit test case for my http APIs, i need to pass the path param to the API endpoint
GetProduct(w http.ResponseWriter, r *http.Request) {
uuidString := chi.URLParam(r, "uuid")
uuid1, err := uuid.FromString(uuidString)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(err.Error()))
return
}
}
I need to test this method and for that i need to pass a valid uuid to r http.Request, please suggest how can i do that, I tried a few options from my test class like
req.URL.Query().Set("uuid", "valid_uuid")
But it did not work. How can I test this method by passing a valid uuid to request?
Let me present my usual solution with
gorillapackage.handler.gofileHere, you use the function
Varsto fetch all of the URL parameters present within thehttp.Request. Then, you've to look for theuuidkey and do your business logic with it.handler_test.gofileFirst, I used the functions provided by the
httptestpackage of the Go Standard Library that fits well for unit testing our HTTP handlers.Then, I used the function
SetUrlVarsprovided by thegorillapackage that allows us to set the URL parameters of anhttp.Request.Thanks to this you should be able to achieve what you need!