httptest 响应重新记录保留旧值

我有一个需要测试的函数:handlerAuthentication


func handlerAuthentication(c *gin.Context) {

    session := Session.GetSession(c)

    var login Login

    err := c.BindJSON(&login)

    if err != nil {

        c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})

        return

    }

    client, err := initClient(c, login)

    fmt.Println("Error: ",err)

    if err != nil {

        fmt.Println("There's an error !")

        c.JSON(http.StatusUnauthorized, gin.H{"error": ErrorWrongLogin})

        return

    }

    err = (*client).Logout(c)

    if err != nil {

        return

    }


    session.Set("username", login.Username)

    session.Set("password", login.Password)

    err = session.Save()

    if err != nil {

        c.JSON(http.StatusInternalServerError, gin.H{"error": "an error occurred during the save of the session:" + err.Error()})

        return

    }

    c.JSON(http.StatusOK, "Connected")

}

为此,我做了这个:


func TestHandlerAuthentication(t *testing.T) {

    UrlOdoo = "https://isi.nc"

    resp := httptest.NewRecorder()

    gin.SetMode(gin.TestMode)

    c, r := gin.CreateTestContext(resp)


    r.POST("/test", func(c *gin.Context) {

        handlerAuthentication(c)

    })


繁花不似锦
浏览 82回答 1
1回答

MMTTMM

我需要为每个测试初始化一个新测试。为此,我将初始化移动到函数:httptest.ResponseRecordert.Run(name,func(t *testing.T)func TestHandlerAuthentication(t *testing.T) {    UrlOdoo = "https://isi.nc"    ctrl := gomock.NewController(t)    defer ctrl.Finish()    Odoo = OdooRPC{createMockOdooClient}    client = mock_odoorpc.NewMockOdooClient(ctrl)    client.EXPECT().Authenticate(gomock.Any(), gomock.Any(), invalidUsername, invalidPassword).AnyTimes().Return(fmt.Errorf("invalid login"))    client.EXPECT().Authenticate(gomock.Any(), gomock.Any(), validUsername, validPassword).AnyTimes().Return(nil)    client.EXPECT().Logout(gomock.Any()).AnyTimes().Return(nil)    session = mock_session.NewMockSession(ctrl)    Session = SessionGetter{createMockSession}    session.EXPECT().Set("username", validUsername).AnyTimes().Return()    session.EXPECT().Set("password", validPassword).AnyTimes().Return()    session.EXPECT().Save().AnyTimes().Return(nil)    for name, test := range map[string]struct {        input Login        want  int    }{        "valid login": {            input: Login{                Username: validUsername,                Password: validPassword,            },            want: 200,        },        "invalid login": {            input: Login{                Username: invalidUsername,                Password: invalidPassword,            },            want: 401,        },    } {        t.Run(name, func(t *testing.T) {            resp := httptest.NewRecorder()            gin.SetMode(gin.TestMode)            c, r := gin.CreateTestContext(resp)            r.POST("/test", func(c *gin.Context) {                handlerAuthentication(c)            })            body, _ := json.Marshal(test.input)            c.Request, _ = http.NewRequest(http.MethodPost, "/test", strings.NewReader(string(body)))            r.ServeHTTP(resp, c.Request)            assert.Equal(t, test.want, resp.Code)        })    }}
打开App,查看更多内容
随时随地看视频慕课网APP