Amit Upa
Amit Upa

Reputation: 367

How to pass json data as request parameter while mocking using gin framework

I have a function to create user which is working properly. Now I have to mock Prepare and SaveUser function inside CreateUser. But that CreateUser require json data as request parameter. Below is my CreateUser function.

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,
    })
}

This is required json data as request parameter for above create user. I want to pass below data while mocking.

{"firstname":"test","email":"[email protected]"}

Below is test case to mock above create user function.

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)
    }
}

Thanks in advance.

Upvotes: 0

Views: 2512

Answers (1)

Eddwin Paz
Eddwin Paz

Reputation: 2868

You need to add a strings.NewReader(string(myjson)) on a new request. Please check this and take it as a template on your current GIN Code.

// 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":"[email protected]"}`

    // 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

}

Upvotes: 1

Related Questions