Skip to content

Instantly share code, notes, and snippets.

@zacksleo
Created April 24, 2019 15:10
Show Gist options
  • Save zacksleo/555ae102e87af209593c5303f441cbfc to your computer and use it in GitHub Desktop.
Save zacksleo/555ae102e87af209593c5303f441cbfc to your computer and use it in GitHub Desktop.
golang customer test using gin & httpexpece
package api
import (
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"gitlab.com/moguyun/api/debug/db"
"gitlab.com/moguyun/api/debug/server"
httpexpect "gopkg.in/gavv/httpexpect.v1"
testfixtures "gopkg.in/testfixtures.v2"
)
func prepareTestDatabase(db *gorm.DB) {
var fixtures *testfixtures.Context
var err error
testfixtures.SkipDatabaseNameCheck(true)
fixtures, err = testfixtures.NewFolder(db.DB(), &testfixtures.MySQL{}, "../fixtures")
if err != nil {
log.Fatal(err)
}
if err = fixtures.Load(); err != nil {
log.Fatal(err)
}
}
var (
fixtures *testfixtures.Context
s *gin.Engine
)
func TestMain(m *testing.M) {
// Open connection with the test database.
// Do NOT import fixtures in a production database!
// Existing data would be deleted
os.Setenv("DATABASE_URL", "web:web@tcp(mysql:3306)/web")
database := db.Connect()
s = server.Setup(database)
prepareTestDatabase(database)
os.Exit(m.Run())
}
func TestGetCustomers(t *testing.T) {
server := httptest.NewServer(s)
defer server.Close()
e := httpexpect.New(t, server.URL)
obj := e.GET("/customers").Expect().Status(http.StatusOK).JSON().Array().Element(0).Object()
obj.ContainsKey("id")
obj.ContainsKey("name")
}
func TestGetCustomer(t *testing.T) {
server := httptest.NewServer(s)
defer server.Close()
e := httpexpect.New(t, server.URL)
obj := e.GET("/customers/1").Expect().Status(http.StatusOK).JSON().Object()
obj.ContainsKey("id")
obj.ContainsKey("name")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment