Gin+Gorm APIをPOSTリクエストでデータ作成をテストする

d yoshikawa
Sep 2, 2018 · 6 min read
  • Go 1.10.2
  • PostgreSQL 10.3
  • Gin 1.3.0
  • Gorm 1.9.1
  • testify1.2.2

下記のようなAPIを書く。

package main

import "github.com/gin-gonic/gin"
import (
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/jinzhu/gorm"
"fmt"
)

var db *gorm.DB
var err error

type Task struct {
gorm.Model
Content string `json:"content"`
}

func main() {
InitDb()
defer db.Close()
r := NewRouter()
r.Run() // listen and serve on 0.0.0.0:8080
}

func InitDb() {
db, err = gorm.Open("postgres", "host=localhost port=5432 user=postgres "+
"dbname=tasklist password=secret sslmode=disable")
if err != nil {
fmt.Println(err)
}

db.DropTable("tasks")
db.AutoMigrate(&Task{})
}

func NewRouter() *gin.Engine {
r := gin.Default()
r.POST("/tasks", func(c *gin.Context) {
var req Task
c.BindJSON(&req)

task := Task{Content: req.Content}
db.Create(&task)

c.JSON(200, task)
})
return r
}

/tasksをPOSTリクエストするとレコードが生成される。
これに対するテストコード。

package main

import (
"testing"
"net/http/httptest"
"github.com/stretchr/testify/assert"
"net/http"
"strings"
)

func TestMain(m *testing.M) {
Setup()
defer db.Close()
m.Run()
}

func Setup() {
InitDb()
}

func TestPost(t *testing.T) {
r := NewRouter()

bodyReader := strings.NewReader(`{"content": "test"}`)

req := httptest.NewRequest("POST", "/tasks", bodyReader)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")

rec := httptest.NewRecorder()

r.ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Code)

var tasks []Task
db.Find(&tasks)

assert.Equal(t, len(tasks), 1)
}
  • testing.M のポインタ型を引数にとるTestMain関数では、 m.Run() の前にSetup、後にTeardownの処理を書ける。

d yoshikawa

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade