gogo-fiber

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?

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