英文:
How do I pass a protobuf object as a row to sqlmock.AddRow in golang?
问题
我正在尝试使用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) 打印出用户名,但它是nil。
我应该如何正确地将protobuf对象传递给addRow?
英文:
I am trying to unit test my go code using sqlmock.
Here is the original code that I am trying to test.
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)
....
}
Here is my unit test
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")
....
}
I am expecting fmt.Printf("user name %+v", user.name) to print user name but its nil.
How do I correctly pass a protobuf object to addRow?
答案1
得分: 1
你在AddRow中使用的数据类型似乎是字符串。在sqlmock中使用protobuf的最佳方法是使用在存根文件中创建的构造函数创建对象,并将其序列化为字符串形式进行存储。然后在实际的方法(enrollCourse)中,你可以获取这个序列化的消息,并将其解组为适当的模型。
英文:
The datatype that you used for AddRow seems to be string. The best way to use protobuf in sqlmock is to create the object with the help of constructor that is created in your stub file and serialise it in the form of string and store it. Then in actual method (enrollCourse
), you can get this serialised message and unmarshal
it into appropriate model.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论