如何测试光纤参数

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

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

huangapple
  • 本文由 发表于 2023年5月2日 14:09:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76152141.html
匿名

发表评论

匿名网友

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

确定