DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.06k stars 408 forks source link

how to mock GORM RecordNotFound ? #180

Closed putrafajarh closed 4 years ago

putrafajarh commented 5 years ago
func GetMerchantConfig(mid uint64) (*model.MerchantConfig, error) {
    DB := bootstrap.App.DB

    var result string
    if DB.Table("merchant_config").Select("trx_minmax").Where("mid = ?", mid).First(&result).RecordNotFound() {
        return nil, errors.New("Please set merchant config")
    }

    config := model.MerchantConfig{}
    json.Unmarshal([]byte(result), &config)

    return &config, nil
}

try to test using below code

rows = mock.NewRows([]string{"trx_minmax"})
mock.ExpectQuery("SELECT trx_minmax FROM merchant_config").WillReturnRows(rows)
_, err = service.GetMerchantConfig(3)
assert.Error(t, err, "Please set merchant config")

and this not work too

mock.ExpectQuery("SELECT trx_minmax FROM merchant_config").WillReturnError(gorm.ErrRecordNotFound)

both code still return nill err

l3pp4rd commented 5 years ago

Sqlmock works as expected, you are missing something. You do not check if the expected query was matched at all by sqlmock