goweb/test/db_test.go

60 lines
1000 B
Go

package test
import (
"site/app/models"
"site/app/models/home"
"testing"
)
func init() {
// 连接数据库
models.ConnectDB()
}
// 测试数据库连接
func TestDbConnect(t *testing.T) {
if models.DB == nil {
t.Error("db connect failed")
}
}
// 测试查询
func TestFind(t *testing.T) {
book := new(home.BookModel)
models.DB.Find(&book)
if book.ID == 0 {
t.Error("not found")
}
}
// 测试创建
func TestCreate(t *testing.T) {
models.DB.Create(&home.BookModel{
Name: "<<test-name>>",
})
if models.DB.Error != nil {
t.Error(models.DB.Error)
}
}
// 测试修改
func TestUpdate(t *testing.T) {
models.DB.
Model(&home.BookModel{}).
Where("name = ?", "<<test-name>>").
Update("name", "<<update-test-name>>")
if models.DB.Error != nil {
t.Error(models.DB.Error)
}
}
// 测试删除
func TestDelete(t *testing.T) {
models.DB.
Where("name = ?", "<<update-test-name>>").
Delete(&home.BookModel{})
if models.DB.Error != nil {
t.Error(models.DB.Error)
}
}