学習備忘ログ

よく使うコードや設定のメモ

【Golang + http/test】リクエストのbodyにjsonを渡す方法

  • サンプルコード bodyJsonにjsonの文字列を代入し、strings.NewReaderで読み込んであげる。
package handler_test

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"

    "github.com/labstack/echo/v4"
    "github.com/stretchr/testify/assert"
)


func TestCreateGroup(t *testing.T) {
    mockDS := store.NewMockStore()
    e := echo.New()

    bodyJSON := `{"name":"test","companyId":9,"categoryId":2,"storeIds":[1,2]}`

    req := httptest.NewRequest(http.MethodPost, "/v1/groups", strings.NewReader(bodyJSON))
    req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
    rec := httptest.NewRecorder()
    c := e.NewContext(req, rec)

  //~~省略
}