如何将路径参数传递给httptest请求?

huangapple go评论77阅读模式
英文:

How to pass path param to httptest request

问题

我正在为我的HTTP API编写单元测试用例,我需要将路径参数传递给API端点。

GetProduct(w http.ResponseWriter, r *http.Request) {
    uuidString := chi.URLParam(r, "uuid")
    uuid1, err := uuid.FromString(uuidString)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        _, _ = w.Write([]byte(err.Error()))
        return
    }
}

我需要测试这个方法,为此我需要向r http.Request传递一个有效的UUID,请建议我如何做到这一点。我在我的测试类中尝试了一些选项,例如:

req.URL.Query().Set("uuid", "valid_uuid")

但它没有起作用。我如何通过向请求传递有效的UUID来测试这个方法?

英文:

I am writing the unit test case for my http APIs, i need to pass the path param to the API endpoint

GetProduct(w http.ResponseWriter, r *http.Request) {
	uuidString := chi.URLParam(r, "uuid")
	uuid1, err := uuid.FromString(uuidString)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = w.Write([]byte(err.Error()))
		return
	}
}

I need to test this method and for that i need to pass a valid uuid to r http.Request, please suggest how can i do that, I tried a few options from my test class like

req.URL.Query().Set("uuid", "valid_uuid") 

But it did not work. How can I test this method by passing a valid uuid to request?

答案1

得分: 3

让我用gorilla包来展示我的常规解决方案。

handler.go 文件

package httpunittest

import (
	"net/http"

	"github.com/gorilla/mux"
)

func GetProduct(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	uuidString, isFound := params["uuid"]
	if !isFound {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	w.Write([]byte(uuidString))
}

在这里,你使用了Vars函数来获取http.Request中的所有URL参数。然后,你需要查找uuid键并进行业务逻辑处理。

handler_test.go 文件

package httpunittest

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gorilla/mux"
	"github.com/stretchr/testify/assert"
)

func TestGetProduct(t *testing.T) {
	t.Run("WithUUID", func(t *testing.T) {
		r := httptest.NewRequest(http.MethodGet, "/products/1", nil) // 注意这个URL是无用的
		r = mux.SetURLVars(r, map[string]string{"uuid": "1"})
		w := httptest.NewRecorder()

		GetProduct(w, r)

		assert.Equal(t, http.StatusOK, w.Result().StatusCode)
	})

	t.Run("Without_UUID", func(t *testing.T) {
		r := httptest.NewRequest(http.MethodGet, "/products", nil) // 注意这个URL是无用的
		w := httptest.NewRecorder()

		GetProduct(w, r)

		assert.Equal(t, http.StatusBadRequest, w.Result().StatusCode)
	})
}

首先,我使用了Go标准库中的httptest包提供的函数,这些函数非常适合对我们的HTTP处理程序进行单元测试。
然后,我使用了gorilla包提供的SetURLVars函数,它允许我们设置http.Request的URL参数。
有了这个,你应该能够实现你的需求!

英文:

Let me present my usual solution with gorilla package.

handler.go file

package httpunittest

import (
	"net/http"

	"github.com/gorilla/mux"
)

func GetProduct(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	uuidString, isFound := params["uuid"]
	if !isFound {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	w.Write([]byte(uuidString))
}

Here, you use the function Vars to fetch all of the URL parameters present within the http.Request. Then, you've to look for the uuid key and do your business logic with it.

handler_test.go file

package httpunittest

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gorilla/mux"
	"github.com/stretchr/testify/assert"
)

func TestGetProduct(t *testing.T) {
	t.Run("WithUUID", func(t *testing.T) {
		r := httptest.NewRequest(http.MethodGet, "/products/1", nil) // note that this URL is useless
		r = mux.SetURLVars(r, map[string]string{"uuid": "1"})
		w := httptest.NewRecorder()

		GetProduct(w, r)

		assert.Equal(t, http.StatusOK, w.Result().StatusCode)
	})

	t.Run("Without_UUID", func(t *testing.T) {
		r := httptest.NewRequest(http.MethodGet, "/products", nil) // note that this URL is useless
		w := httptest.NewRecorder()

		GetProduct(w, r)

		assert.Equal(t, http.StatusBadRequest, w.Result().StatusCode)
	})
}

First, I used the functions provided by the httptest package of the Go Standard Library that fits well for unit testing our HTTP handlers.
Then, I used the function SetUrlVars provided by the gorilla package that allows us to set the URL parameters of an http.Request.
Thanks to this you should be able to achieve what you need!

huangapple
  • 本文由 发表于 2022年12月23日 21:35:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/74900245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定