gpt4 book ai didi

go - 如何将 TestContext 传递给不接受 Gin 上下文作为参数的方法?

转载 作者:行者123 更新时间:2023-12-01 22:36:26 25 4
gpt4 key购买 nike

我正在为基于 Gin-Gonic 的服务编写测试。
我有一个不接受 gin 上下文作为参数的处理程序。
例子:

func (h *handler) Handler1(isTrue bool) func(*gin.Context) {

return func(c *gin.Context) { .. Do Something }
}

我想为这个方法编写测试,但我不知道我应该如何将模拟 Gin Context 传递给它。

如果我为接受 Gin 上下文作为参数的任何其他方法(如下面的 Ping 方法)执行此操作,我将这样做。
func (*handler) Ping(c *gin.Context) {
c.String(http.StatusOK, "Pong")
c.Writer.WriteHeaderNow()
} // Method

在测试中:
handler := NewHandler()
recorder := httptest.NewRecorder()
mockGinContext, _ := gin.CreateTestContext(recorder)
handler.Ping(mockGinContext)

对于 Handler1,我应该如何将 TestContext 传递给它?

最佳答案

您应该在测试中使用相同的策略:

var h *handler
h = ... // however you create *handler
recorder := httptest.NewRecorder()
mockGinContext, _ := gin.CreateTestContext(recorder)
// note that you will have to know do you want to test both,
// or just one of the handlers returned from Handler1
h.Handler1(true)(mockGinContext)
h.Handler1(false)(mockGinContext)

关于go - 如何将 TestContext 传递给不接受 Gin 上下文作为参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61998446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com