前提・実現したいこと
GolangのGinフレームワークのテストを書いているのですが、テストで送ったデータをC.PostFormで受け取ることができません。解決策が分かる方、ご教示下さると助かります。
###現状
下記のコードだと、controllerのSignup関数の中にある、
C.PostForm("email")
c.PostForm("name")
c.PostForm("password")
で、送ったデータを取得することができませんでした。
”全ての情報を入力してください(All information should be filled in.)”という、Signup関数内のエラーが返って来るので、ルーターなどの問題ではないと思います。
該当のソースコード
test
func InitTestUserCreate(body map[string]interface{}) *httptest.ResponseRecorder { r := gin.Default() app := new(apps.Application) app.CreateTest(r) w := httptest.NewRecorder() b, _ := json.Marshal(body) req, _ := http.NewRequest(http.MethodPost, "/api/test/signup", strings.NewReader(string(b))) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) return w } func TestUserCreate(t *testing.T) { t.Run("it should return success", func(t *testing.T) { defer database.DropAllTable() body := map[string]interface{}{ "name": "User Test", "email": "user@email.com", "password": "password", } w := InitTestUserCreate(body) t.Log(w) assert.Equal(t, http.StatusOK, w.Code) }) }
controller
func (uc *UserController) Signup(c *gin.Context) { var user entity.User email := c.PostForm("email") name := c.PostForm("name") pass := c.PostForm("password") // ↑ここで、テストから送られたデータを受け取りたい... if name == "" || email == "" || pass == "" { res := response.BadRequest("全ての情報を入力してください(All information should be filled in.)") c.JSON(res.Status, res) } else { if _, err := uc.Repository.FindByEmail(email); err == nil { res := response.Conflict("このメールアドレスは既に登録されています(This e-mail has already been registered)") c.JSON(res.Status, res) } else { passwordEncrypt, _ := middleware.PasswordEncrypt(pass) user = entity.User{ Name: name, Email: email, Password: passwordEncrypt, } if err := uc.Repository.Create(&user); err != nil { res := response.BadRequest("予期せぬエラーが発生しました(An unexpected error has occured)") c.JSON(res.Status, res) } else { userID := user.ID middleware.Login(c, userID) res := response.SuccessResponse("") c.JSON(res.Status, res) } } } }
質問に不備があれば、再掲させていただきます。
ご回答の程、宜しくお願いします。
まだ回答がついていません
会員登録して回答してみよう