2

I have the following test function.

func (s *Suite) Test_delete() {
    var (
        id       = uuid.New()
        name     = "test"
        quantity = 2
    )
    s.mock.ExpectQuery(regexp.QuoteMeta(
        `SELECT * FROM "items" WHERE code = $1 AND "items"."deleted_at" IS NULL`,
    )).
        WithArgs(id).
        WillReturnRows(sqlmock.NewRows([]string{"code", "name", "quantity"}).
            AddRow(id, name, quantity))

    err := s.repository.DeleteItem(id.String())
    require.NoError(s.T(), err)
}

Now the problem is trying to scan the id variable into the row for the column code. In my Product struct, I have code defined as follows.

type Item struct {
    Code      uuid.UUID      `gorm:"type:uuid;primaryKey" json:"code"`
    Name      string         `json:"name" validate:"required"`
    Quantity  int            `json:"qty" validate:"required,min=0"`
    DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

func (i *Item) BeforeCreate(tx *gorm.DB) (err error) {
    if i.Code == uuid.Nil {
        i.Code = uuid.New()
    }
    return
}

Now the problem is when I try to run the test function, it is somehow unable to scan uuid.UUID into UUID even though they are both the same types. Here is the exact error message.

msql: Scan error on column index 0, name "code": Scan: unable to scan type uuid.UUID into UUID

Could someone help me on this part?

Richard
  • 7,037
  • 2
  • 23
  • 76
  • Not an answer, but I was reading uuid code, and it works only with string or []byte types it seems, for other types it will throw your error - https://github.com/google/uuid/blob/master/sql.go#L15 – Alex Pliutau Feb 02 '23 at 10:25

1 Answers1

0

Read this. I assume there is type casting error. Changing WillReturnRows(sqlmock.NewRows([]string{"code", "name", "quantity"}).AddRow(id, name, quantity))->WillReturnRows(sqlmock.NewRows([]string{"code", "name", "quantity"}).AddRow(id.String(), name, quantity)) may help.