我正在尝试使用 sqlmock 对我的 go 代码进行单元测试。这是我要测试的原始代码。
func enrollCourse(db *gorm.DB, user_id string ,course_id string) error {
user := &usermodels.User{}
ref := db.First(user, "uuid = ?", user_id)
userPb := user.Protobuf()
fmt.Printf("user name %+v", user.name)
....
}
这是我的单元测试
func TestEnrollCourse(t *testing.T){
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
rows := sqlmock.NewRows([]string{"user_id","user_name"}).
AddRow(1, "John")
mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "users" WHERE uuid = $1`)).WithArgs("user-fd3746c8-d32f-4fb8-8f6a-b6d72dcf2969").WillReturnRows(rows)
gdb, err := gorm.Open(postgres.New(postgres.Config{
Conn: db,
}), &gorm.Config{})
enrollCourse(gdb, "user-fd3746c8-d32f-4fb8-8f6a-b6d72dcf2969", "english_course")
....
}
我期待 fmt.Printf("user name %+v", user.name) 打印用户名,但它为零。如何正确地将 protobuf 对象传递给 addRow?
侃侃尔雅
相关分类