I've been trying to mock a fiber.Ctx but I have not been able to make it work I have been getting this error:
--- FAIL: TestCheckHeaders (0.00s) panic: runtime error: invalid memory address or nil pointer dereference [recovered] panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x12085f0]
The code that I am trying to test:
CheckHeaders.go
package middleware
import "github.com/gofiber/fiber/v2"
func CheckHeaders(c *fiber.Ctx) error {
headers := c.GetReqHeaders()
if headers["headerValue"] == "true"{
return c.Next()
} else {
return c.SendStatus(401)
}
}
CheckHeaders_test.go
package middleware
import (
"testing"
"github.com/gofiber/fiber/v2"
)
func TestCheckHeaders(t *testing.T) {
type args struct {
c *fiber.Ctx
}
fiberContext := fiber.Ctx{}
tests := []struct {
name string
args args
wantErr bool
}{
{name: "test 1",
args: args{c: &fiberContext},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := CheckHeaders(tt.args.c); (err != nil) != tt.wantErr {
t.Errorf("CheckHeaders() error = %v, wantErr %v", err,tt.wantErr)
}
})
}
}
This was how I set up a new context that I could manipulate for testing. Hope it helps.
app := fiber.New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c
will be a fresh *fiber.Ctx
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With