github.com/zooyer/miskit@v1.0.71/micro/dao_test.go (about) 1 package micro 2 3 import ( 4 "context" 5 "gorm.io/gorm" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 type testModel struct { 12 Model 13 Name string `json:"name"` 14 Age int `json:"age"` 15 } 16 17 func (t testModel) TableName() string { 18 return "test" 19 } 20 21 func TestNewDao(t *testing.T) { 22 var ctx = context.Background() 23 24 db, err := OpenDB("sqlite", ":memory:", nil) 25 if err != nil { 26 t.Fatal(err) 27 } 28 29 db = db.Debug() 30 31 if err = db.AutoMigrate(new(testModel)); err != nil { 32 t.Fatal(err) 33 } 34 35 getDB := func(ctx context.Context) *gorm.DB { 36 return db.WithContext(ctx) 37 } 38 39 dao := NewDao(getDB, new(testModel)) 40 41 var test = testModel{ 42 Name: "dog", 43 } 44 45 if err = dao.Create(ctx, nil, &test); err != nil { 46 t.Fatal(err) 47 } 48 t.Logf("%#v", test) 49 50 test.ID = 0 51 if err = dao.Create(ctx, nil, &test); err != nil { 52 t.Fatal(err) 53 } 54 t.Logf("%#v", test) 55 56 count, err := dao.Count(ctx, nil) 57 if err != nil { 58 t.Fatal(err) 59 } 60 61 assert.Equal(t, int64(2), count) 62 }