gpt4 book ai didi

unit-testing - 如何在 gin 的测试上下文中设置主机?

转载 作者:行者123 更新时间:2023-12-01 21:13:58 27 4
gpt4 key购买 nike

我想为 Controller 编写单元测试,但我不断收到运行时错误。我发现这是由于没有 Host根据要求,ClientIP()方法和请求体。如何在测试上下文中设置它们?

这是我到目前为止得到的。它在 Host: c.Request.Host 线上失败.

Controller :

type loggingControllers struct {
LoggingService services.InterfaceLogging
}

func (l *loggingControllers) RegisterError(c *gin.Context) {
errorEvent := models.Error{
Badges: map[string]string{},
Host: c.Request.Host,
ClientIP: c.ClientIP(),
UserAgent: c.Request.UserAgent(),
Count: 1,
Timestamp: time.Now().Unix(),
}

err := json.NewDecoder(c.Request.Body).Decode(&errorEvent)
if err != nil {
utils.RespondWithError(c, http.StatusInternalServerError, err.Error())
return
}

go l.LoggingService.SaveError(errorEvent)

utils.RespondWithSuccess(c)
}

func GetLoggingControllerMock() loggingControllers {
loggingServiceMock := services.GetLoggingServiceMock()

return loggingControllers{
LoggingService: &loggingServiceMock,
}
}

单元测试:

func TestLoggingControllers(t *testing.T) {
loggingControllers := GetLoggingControllerMock()

w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

loggingControllers.RegisterError(c)
}

错误消息:
--- FAIL: TestLoggingControllers (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=0x38 pc=0x15238ec]

最佳答案

感谢 Adrian 的评论,我找到了解决方案。

func TestLoggingControllers(t *testing.T) {
loggingControllers := GetLoggingControllerMock()

w := httptest.NewRecorder()
c, r := gin.CreateTestContext(w)

r.POST("/", loggingControllers.RegisterError)

c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBuffer([]byte("{}")))

r.ServeHTTP(w, c.Request)

if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
}

关于unit-testing - 如何在 gin 的测试上下文中设置主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61148343/

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