Hi there, I'm currently trying to write tests for my very simple microservice. I'm using httprouter and I've tried to use the answers from this question: https://stackoverflow.com/questions/43502432/how-to-write-test-with-httprouter but I just get a runtime error or the parameters don't seem to get passed through to the function.
My test file is here on Github: https://github.com/AndrewRMorgan/url-shortener/blob/master/main_test.go
Any help would be greatly appreciated.
评论:
epiris:
qu33ksilver:In case you are curious why no one answered, you failed to provide the two most important things. The error and the code from the offending frame within the stack trace. I assume you omitted them because you felt it was not related, but until you are familiar enough with a language (this applies to all languages, not just Go) to no longer get stuck on these sort of problems than you are not familiar enough to omit details. Just friendly advice for getting help and avoiding frustrating XY problem dialogs. If you are still stuck post a runnable example and I'll tell you what is wrong.
sethammons:What is the error you are getting and at which line no. ? You have to be a bit more specific.
I avoid httprouter because of its non-conformity to the stdlib. If I go with a non-stdlib router these days, I use chi.
As for testing, what I've done in the past is something like:
e := someStructWithAnHandlerFunction{} rw := httptest.NewRecorder() r, _ := http.NewRequest("GET", "/blah", nil) params := httprouter.Params{} params = append(params, httprouter.Param{Key: "token", Value: "my token value"}) // GetSomeEndpoint is the handler function under test e.GetSomeEndpoint(rw, r, params) // response if got, want := rw.Code, http.StatusOk; got != want { t.Errorf("got %d, want %d", got, want) }
Edit: formatting
