Tuesday, July 23, 2024
HomeGolanghttptest.NewRequest find out how to embody path with worth? - Getting Assist

httptest.NewRequest find out how to embody path with worth? – Getting Assist

I’m attempting to check http handler with what’s described in Revisiting HTTP Handlers | most important | Be taught Go along with checks

I’ve the next code (skimmed for brevity):

e mail := "myemail@take a look at.me"

urlPath := fmt.Sprintf("http://take a look at.com/%s", e mail)

request := httptest.NewRequest(http.MethodPost, urlPath, nil)
response := httptest.NewRecorder()

handleEmailCheck(response, request)

The route is one thing like

router.HandleFunc("POST /customers/{e mail}", handleEmailCheck)

I consider the route/router will not be getting used since I’m solely testing the handler in isolation. I’ve tried with

urlPath := fmt.Sprintf("http://take a look at.com/customers/%s", e mail)

urlPath := fmt.Sprintf("/%s", e mail)

But it surely at all times offers me 400 as a result of the next fails (returns “”)

e mail := r.PathValue("e mail")

If I run the app and take a look at with Postman, it’s working wonderful. Is there any particular necessities or setup wanted for httptest to be able to move path worth?


r, err := http.NewRequest(methodology, path, physique)
r.SetPathValue("key", "worth")

Instance in:

1 Like

Precisely. In your take a look at it’s essential do one thing to arrange your mux/routes. Take a look at the examples in http/httptest. It is a submit that exhibits the way you would possibly write some checks:

And one other method is to separate out your mux logic after which simply re-use that in your checks. One thing alongside the strains of this:

Going with the second possibility, let’s create a contrived instance primarily based on what you are attempting to check:

func most important() {
	mux := newAppMux()
	http.ListenAndServe(":9090", mux)

func newAppMux() *http.ServeMux {
	router := http.NewServeMux()
	router.HandleFunc("POST /customers/{e mail}", handleEmailCheck)
	return router

func handleEmailCheck(w http.ResponseWriter, r *http.Request) {
	e mail := r.PathValue("e mail")
	if len(e mail) > 0 {
		fmt.Fprintf(w, `{ "e mail" : "%v" }`, e mail)
	} else {
		fmt.Fprint(w, http.StatusText(http.StatusNotFound))

To check it:

func TestHandleEmailCheck(t *testing.T) {
	ts := httptest.NewServer(newAppMux())
	defer ts.Shut()

	shopper := ts.Consumer()
	res, err := shopper.Submit(fmt.Sprintf("%v/customers/take a look at@take a look at.com", ts.URL), "utility/json", strings.NewReader(`{ "request": "physique" }`))
	if err != nil {
		t.Errorf("Wasn't anticipating error. Received: %v", err)

	resBody, err := io.ReadAll(res.Physique)
	if err != nil {
		t.Errorf("Wasn't anticipating error. Received: %v", err)
	anticipating := `{ "e mail" : "take a look at@take a look at.com" }`
	if string(resBody) != anticipating {
		t.Errorf("Surprising response.nnExpected: %vnGot: %s", anticipating, resBody)

Hopefully this is sufficient to get you began!

1 Like

Thank your very a lot, each of you. I’ve tried each method and it’s working as anticipated. Nevertheless, I’m going with @GonzaSaya’s method since it’s a lot easier and cleaner for my part.

It’s a query of what you might be testing. Allow code protection and take a look at each options to see what I imply. That mentioned, each approaches are wonderful and I’m glad you discovered an answer!

1 Like

Sure, you might be appropriate. I feel your method is extra suited to integration take a look at? I’m planning on doing a separate integration take a look at half in a while so I’ll undoubtedly go together with mux one by mocking the server.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments