1

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?

baitendbidz
  • 187
  • 3
  • 19
  • 2
    show your server side code. – Daniel A. White Jan 27 '23 at 22:29
  • Hey, this question looks familiar. We're able to provide much better answers if your question includes an [mcve] -- code that we can compile and run locally to reproduce the behavior you're asking about. – larsks Jan 27 '23 at 22:41

1 Answers1

0

It seems I have to pass in a non empty request body ( source code ), e.g.

requestBody := bytes.NewReader(make([]byte, 10, 10))

then I can setup the request like so

request, _ := http.NewRequest(http.MethodPost, "/my-route", requestBody)
baitendbidz
  • 187
  • 3
  • 19