简体   繁体   English

go - 如何模拟 fiber 上下文

[英]go - How to mock fiber context

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:我一直在尝试模拟 fiber.Ctx 但我无法使其正常工作我一直收到此错误:

--- 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] ---失败:TestCheckHeaders(0.00s)恐慌:运行时错误:无效内存地址或零指针取消引用[已恢复]恐慌:运行时错误:无效内存地址或零指针取消引用[信号SIGSEGV:分段违规代码= 0x1地址= 0x0 pc =0x12085f0]

The code that I am trying to test:我要测试的代码:

CheckHeaders.go 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 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)
            }
        })
    }
   }

You can create your own interface with methods you need to use from fiber.Ctx struct and make mock for the interface.您可以使用需要从fiber.Ctx结构使用的方法创建自己的接口,并为该接口制作模拟。

After that you are going to handle fiber.Ctx as implementation of for example Ctxer interface so you will be able to mock it using https://github.com/golang/mock and use the mock in your tests.之后,您将处理fiber.Ctx作为例如Ctxer接口的实现,因此您将能够使用https://github.com/golang/mock模拟它并在您的测试中使用模拟。

It's gonna look like this它会看起来像这样

type Ctxer interface {
    GetReqHeaders() map[string]string
    Next() (err error)
    SendStatus(status int) error
}

func CheckHeaders(c Ctxer) error {
    headers := c.GetReqHeaders()
    if headers["headerValue"] == "true" {
        return c.Next()
    } else {
        return c.SendStatus(401)
    }
}

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 . c将是一个新的*fiber.Ctx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM