0

我有一个功能可以创建正常工作的用户。现在我必须在Prepare and SaveUser里面模拟函数CreateUser。但这CreateUser需要 json 数据作为请求参数。下面是我的CreateUser功能。

func (server *Server) CreateUser(c *gin.Context) {
    errList = map[string]string{}
    user := models.User{}
    if err := c.ShouldBindJSON(&user); err != nil {
        log.Println(err)
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})  **//every time return from here with error -> invalid request**
        return
    }
    user.Prepare()

    userCreated, err := sqlstore.SaveUser(&user)
    if err != nil {
        formattedError := formaterror.FormatError(err.Error())
        errList = formattedError
        c.JSON(http.StatusInternalServerError, gin.H{
            "status": http.StatusInternalServerError,
            "error":  errList,
        })
        return
    }

    c.JSON(http.StatusCreated, gin.H{
        "status":   http.StatusCreated,
        "response": userCreated,
    })
}

这是上述创建用户所需的 json 数据作为请求参数。我想在模拟时传递以下数据。

{"firstname":"test","email":"test@test.com"}

下面是模拟上面创建用户功能的测试用例。

type UserMock struct {
    mock.Mock
}
func (u *UserMock) Prepare() (string, error) {
    args := u.Called()
    return args.String(0), args.Error(1)
}
func (u *UserMock) SaveUser() (string, error) {
    args := u.Called()
    return args.String(0), args.Error(1)
}
func TestCreateUser(t *testing.T) {
    gin.SetMode(gin.TestMode)
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)
    **//how to json data as request parameter**
    uMock := UserMock{}
    uMock.On("Prepare").Return("mocktest", nil)
    server := Server{}
    server.CreateUser(c)
    if w.Code != 201 {
        t.Error("Unexpected status code found : ",w.Code)
    }
}

提前致谢。

4

1 回答 1

1

您需要在新请求中添加strings.NewReader(string(myjson)) 。请检查这一点并将其作为您当前 GIN 代码的模板。

// TestCreateUser new test
func TestCreateUser(t *testing.T) {

    // Setup Recorder, TestContext, Router
    router := getRouter(true)
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)

    // set JSON body
    jsonParam := `{"firstname":"test","email":"test@test.com"}`

    // Mock HTTP Request and it's return
    req, err := http.NewRequest("POST", "/user", strings.NewReader(string(jsonParam)))

    // make sure request was executed
    assert.NoError(t, err)

    // Serve Request and recorded data
    router.ServeHTTP(w, req)

    // Test results
    assert.Equal(t, 200, w.Code)
    assert.Equal(t, nil, w.Body.String()) 
    // check your response since nil isn't valid return

}
于 2020-03-26T20:22:56.833 回答