Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to test fiber 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to change the Params field using ctx.Route().Params, but it didn’t work

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading