英文:
How to test fiber params
问题
我需要为其中一个处理程序编写一个测试。在处理程序内部,我有类似以下的代码:
ctx.Params("id")
是否可以创建一个上下文,以便在处理程序内部Params不为nil?
我尝试使用ctx.Route().Params
来更改Params字段,但它没有起作用。
英文:
I need to write a test for one of the handlers. Inside the handler I have somethings like:
ctx.Params("id")
Is it possible to create a context so that inside the handler Params are not nil?
I tried to change the Params field using ctx.Route().Params, but it didn't work
答案1
得分: 2
我认为最好使用(*App).Test,让它从请求中创建一个上下文。像这样:
package main
import (
"fmt"
"net/http/httptest"
"testing"
"github.com/gofiber/fiber/v2"
)
func handler(c *fiber.Ctx) error {
id := c.Params("id")
fmt.Println("Params:", id)
return nil
}
func TestXxx(t *testing.T) {
app := fiber.New()
app.Get("/hello/:id", handler)
req := httptest.NewRequest("GET", "/hello/man", nil)
_, _ = app.Test(req, -1)
}
$ go test . -v
=== RUN TestXxx
Params: man
--- PASS: TestXxx (0.00s)
PASS
ok m 0.002s
英文:
I think it's better to use (*App).Test and let it create a context from the request. Like this:
package main
import (
"fmt"
"net/http/httptest"
"testing"
"github.com/gofiber/fiber/v2"
)
func handler(c *fiber.Ctx) error {
id := c.Params("id")
fmt.Println("Params:", id)
return nil
}
func TestXxx(t *testing.T) {
app := fiber.New()
app.Get("/hello/:id", handler)
req := httptest.NewRequest("GET", "/hello/man", nil)
_, _ = app.Test(req, -1)
}
$ go test . -v
=== RUN TestXxx
Params: man
--- PASS: TestXxx (0.00s)
PASS
ok m 0.002s
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论