Home > OS >  How do I pass a protobuf object as a row to sqlmock.AddRow in golang?
How do I pass a protobuf object as a row to sqlmock.AddRow in golang?

Time:11-28

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?

CodePudding user response:

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.

  • Related