But it always gives me 400 because the following fails (returns “”)
email := r.PathValue("email")
If I run the app and test with Postman, it is working fine. Is there any special requirements or setup needed for httptest in order to pass path value?
Exactly. In your test you need to do something to set up your mux/routes. Check out the examples in http/httptest. This is a post that shows how you might write some tests:
And another approach is to split out your mux logic and then just re-use that in your tests. Something along the lines of this:
Going with the second option, let’s create a contrived example based on what you are trying to test:
Thank your very much, both of you. I have tried both approach and it is working as expected. However, I am going with @GonzaSaya’s approach since it is much simpler and cleaner in my opinion.
It’s a question of what you are testing. Enable code coverage and test both solutions to see what I mean. That said, both approaches are fine and I’m glad you found a solution!
Yes, you are correct. I think your approach is more suited for integration test? I am planning to do a separate integration test part later on so I will definitely go with mux one by mocking the server.