Skip to content

Instantly share code, notes, and snippets.

@wtask
Last active April 26, 2019 15:28
Show Gist options
  • Save wtask/d95dc6a31d9cb0a3c18bbc8d7e5ce7c4 to your computer and use it in GitHub Desktop.
Save wtask/d95dc6a31d9cb0a3c18bbc8d7e5ce7c4 to your computer and use it in GitHub Desktop.
Go: organize your tests with "suits" to get setup/teardown for group of tests and make initialization without using init() function and any testing frameworks!
package service
import (
"fmt"
"testing"
"github.com/jinzhu/gorm"
".../service/model"
)
type test func(t *testing.T)
// CoolServiceSuite - group of CoolService tests
func CoolServiceSuite(s CoolService, testDB *gorm.DB) []test {
return []test{
ServiceMethodFirst(s, testDB),
ServiceMethodNext(s, testDB),
}
}
// ServiceMethodFirst - make test for CoolService.MethodFirst()
func ServiceMethodFirst(s CoolService, testDB *gorm.DB) test {
return func(t *testing.T) {
t.Log("TEST service.CoolService.MethodFirst()")
value, err := s.MethodFirst()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if value != "first is cool" {
t.Errorf("Unexpected result: %s", value)
}
// check DB changes with testDB
}
}
// ServiceMethodNext - make test for CoolService.MethodNext()
func ServiceMethodNext(s CoolService, testDB *gorm.DB) test {
return func(t *testing.T) {
// test something
}
}
// setupDB - creates independent db connection to track changes made by CoolService,
// returns *gorm.DB only as example
func setupDB() *gorm.DB {
// read config, find DSN ...
db, err := gorm.Open(...)
if err != nil {
panic(err)
}
// prepare something or make migrations ...
return db
}
func TestCoolService(t *testing.T) {
testDB := setupDB()
// additional setup ...
defer func() {
// tear down
testDB.Close()
// ...
}()
cool, err := NewCoolService()
for i, test := range CoolServiceSuite(cool, testDB) {
t.Run(fmt.Sprintf("test #%d", i), test)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment