Go语言 如何测试请求是否因无效的内容类型而失败?

qlvxas9a  于 2023-02-01  发布在  Go
关注(0)|答案(1)|浏览(113)

我将Chi与内置的AllowContentType中间件一起使用。

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
}

我想编写一个测试来检查如果内容类型不是 application/json,路由是否会响应415,我尝试过

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)
    }
}

不幸的是,测试失败
应为状态代码415,但得到的是201
所以看起来中间件通过了,路由处理器发回了成功代码。2我如何修正测试以确保中间件用415拒绝请求呢?

oymdgrw7

oymdgrw71#

看起来我必须传入一个非空的请求主体(源代码),例如:

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

然后我可以这样设置请求

request, _ := http.NewRequest(http.MethodPost, "/my-route", requestBody)

相关问题