DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.05k stars 406 forks source link

GORM model with time.Time type error #227

Open reyhansofian opened 4 years ago

reyhansofian commented 4 years ago

Hi, I have an issue with mocking for GORM that uses timestamp on the model. For example, I have this model

type SomeModel struct {
    CreatedAt time.Time      `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"created_at"`
    UpdatedAt time.Time      `gorm:"column:updated_at;default:CURRENT_TIMESTAMP" json:"updated_at"`
    DeletedAt *time.Time     `gorm:"column:deleted_at" json:"deleted_at"`
}

I know that we can use sqlmock.NewWithDSN for this case and this is how I initiate the database mock connection

    db, mock, err := sqlmock.NewWithDSN("mysql://user:password@(localhost)/dbname?charset=utf8&parseTime=true&loc=Local")
    if err != nil {
        Expect(err).ShouldNot(HaveOccurred())
    }

    grm, err = gorm.Open("sqlmock", db)
    if err != nil {
        Expect(err).ShouldNot(HaveOccurred())
    }

then this error happens

...
sql: Scan error on column index 5, name \"created_at\": unsupported Scan, storing driver.Value type string into type *time.Time
...

after looking at GORM issues, this should be solved if we're using the parseTime=True on the dsn. Ref: this issue and this issue.

Apparently, GORM didn't parse the dsn correctly. I'm not sure how to fix this issue. I would gladly make a fix for this issue if you can lead me on how to fix this issue properly. Thanks!

l3pp4rd commented 4 years ago

Sqlmock is a mock database, it does not know that you use gorm or any other thing underneath. If you use non standard arguments to sql value converter. You need to register it for mock database via options

hielfx commented 3 years ago

Sqlmock is a mock database, it does not know that you use gorm or any other thing underneath. If you use non standard arguments to sql value converter. You need to register it for mock database via options

Is there a sqlmock options configuration with gorm example showing how to achieve the time conversion?