我尝试用 sqlmock 测试 gorm 的东西。
我的模型看起来像:
type Worker struct {
Model
NetworkAddress string
Name string
Version string
Available bool
Services []Service `gorm:"foreignKey:WorkerId;references:Id"`
}
我收到以下错误:
unsupported data type: &[]: Table not set, please set it like: db.Model(&user) or db.Table("users")
考试:
db, mock := createMock(t)
repo = db
row := sqlmock.NewRows([]string{"id", "network_address", "version", "name"}).AddRow("1", "test", "1.0", "test")
mock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `workers` WHERE `workers`.`id` = ? AND `workers`.`deleted_at` IS NULL ORDER BY `workers`.`id` LIMIT 1")).
WithArgs(1).
WillReturnRows(row)
db.Con.Table("Services")
worker, err := FindWorkerByConds(1)
if err != nil {
t.Errorf("expected query to be executred, got error %s", err)
}
if worker.Name != "test" {
t.Error("expected name to be test")
}
功能:
var (
worker *models.Worker
tx *gorm.DB
)
worker = &models.Worker{}
// use builder to load preload conditions
tx = repo.Build().Preload("Services").First(worker, conds)
return worker, tx.Error
Build 只是一个返回的助手*gorm.DB
运行该示例按预期工作,但尝试对其进行单元测试失败。