Home > Backend Development > Golang > How to pass protobuf object as a row to sqlmock.AddRow in golang?

How to pass protobuf object as a row to sqlmock.AddRow in golang?

PHPz
Release: 2024-02-11 11:03:07
forward
515 people have browsed it

如何将 protobuf 对象作为一行传递给 golang 中的 sqlmock.AddRow?

php小编小新在这里为大家介绍一个问题:如何将 protobuf 对象作为一行传递给 golang 中的 sqlmock.AddRow?在使用 golang 开发中,我们经常会遇到需要将 protobuf 对象转换为数据库行的情况。而 sqlmock 是一个常用的 mock 数据库操作的工具,但是如何将 protobuf 对象传递给 sqlmock 的 AddRow 方法却是一个需要解决的问题。接下来,我们将详细介绍如何解决这个问题,让大家能够更好地应用 protobuf 和 sqlmock。

问题内容

我正在尝试使用 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)
    ....
}
Copy after login

这是我的单元测试

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")
    ....
}
Copy after login

我期待 fmt.printf("user name %+v", user.name) 打印用户名,但它为零。 如何正确地将 protobuf 对象传递给 addrow?

解决方法

您用于 AddRow 的数据类型似乎是字符串。在 sqlmock 中使用 protobuf 的最佳方法是借助存根文件中创建的构造函数来创建对象,并将其以字符串形式序列化并存储。然后在实际方法(enrollCourse)中,您可以获取此序列化消息并将 unmarshal 转换为适当的模型。

The above is the detailed content of How to pass protobuf object as a row to sqlmock.AddRow in golang?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template