Skip to content

How to write unit test case using golang echo, when we have multipart form files and json request? #2378

Answered by aldas
SajaiPrathap070 asked this question in Q&A
Discussion options

You must be logged in to vote

Try something like this

func TestMultiPartForm(t *testing.T) {
	e := echo.New()

	bodyBuffer := new(bytes.Buffer)
	mw := multipart.NewWriter(bodyBuffer) // see https://pkg.go.dev/mime/multipart
	mw.WriteField("id", "1")
	mw.WriteField("json", `{"ok":true}`)
	mw.Close()

	req := httptest.NewRequest(http.MethodPost, "/", bodyBuffer)
	rec := httptest.NewRecorder()
	req.Header.Set(echo.HeaderContentType, mw.FormDataContentType())

	c := e.NewContext(req, rec)

	type payload = struct {
		ID   int    `form:"id"`
		JSON string `form:"json"`
	}
	u := new(payload)

	err := c.Bind(u)
	if assert.NoError(t, err) {
		assert.Equal(t, 1, u.ID)
		assert.Equal(t, `{"ok":true}`, u.JSON)
	}
}

and if you nee…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by lammel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants