I'm using Chi with the builtin AllowContentType middleware. Given this sample
package main
import (
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
http.ListenAndServe(":3000", GetRouter())
}
func GetRouter() *chi.Mux {
apiRouter := chi.NewRouter()
apiRouter.Use(middleware.AllowContentType("application/json"))
apiRouter.Post("/my-route", func(responseWriter http.ResponseWriter, request *http.Request) {
responseWriter.WriteHeader(http.StatusCreated)
})
return apiRouter
}
I want to write a test to check if a route responds with a 415 if the content type is not application/json, I tried
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestGetRouter(testing *testing.T) {
router := GetRouter()
responseRecorder := httptest.NewRecorder()
request, _ := http.NewRequest(http.MethodPost, "/my-route", nil)
request.Header.Set("Content-Type", "text/xml")
router.ServeHTTP(responseRecorder, request)
if responseRecorder.Code != http.StatusUnsupportedMediaType {
testing.Errorf("Expected statuscode %d but got %d", http.StatusUnsupportedMediaType, responseRecorder.Code)
}
}
Unfortunately the test fails with
Expected statuscode 415 but got 201
so it seems the middleware passes and the route handler sends back the success code. How can I fix the test to ensure the middleware rejects the request with a 415?