如何解决测试 row.scan 时如何模拟 sqlmock 错误
我正在尝试模拟以下函数。我正在努力让它测试 rows.next() 返回。
func (u *userRepository) GetList(idClient int) ([]UserPublic,rest_errors.RestErr) {
stmt,err := u.client.Prepare(queryGetUserList)
if err != nil {
logger.Error("Error when trying to prepare get user list statement",err)
return nil,rest_errors.NewInternalServerError("Error when tying to get user list",errors.New("database error"))
}
defer stmt.Close()
var userList []UserPublic
var user UserPublic
rows,errStmt := stmt.Query(idClient)
if errStmt != nil {
logger.Error("Error when trying to query the user list",errStmt)
return nil,rest_errors.NewInternalServerError("Error when tying to get the user list",errors.New("database error"))
}
for rows.Next() {
if getErr := rows.Scan(&user.Id,&user.Name,&user.FirstSurname,&user.SecondSurname,&user.Email,&user.BirthDate,&user.identityNumbersql,&user.clinicalNumbersql,&user.cardsql,&user.phoneNumbersql,&user.Role,&user.DateCreated); getErr != nil {
logger.Error("Error when trying to get user list",getErr)
return nil,MysqL_utils.ParseError(getErr)
}
userList = append(userList,user)
}
return userList,nil
}
这是我的测试用例:
func TestUserGetListErrorScanRows (t *testing.T) {
db,mock,err = getMockDB(t)
defer db.Close()
s := NewUserDaoMysqL(db)
t.Run("Error scanning rows",func(t *testing.T) {
rows := sqlmock.NewRows([]string{"id","name","first_surname","second_surname","email","birth_date","identity_number","clinical_number","card","phone_number","role","date_created"}).AddRow(0,user.Name,user.FirstSurname,user.SecondSurname,user.Email,user.BirthDate,user.IdentityNumber,user.ClinicalNumber,user.Card,user.PhoneNumber,user.Role,user.DateCreated).
RowError(1,fmt.Errorf("row error"))
mock.ExpectPrepare("SELECT (.+) FROM user").ExpectQuery().WillReturnRows(rows)
rs,errDb := db.Query("SELECT (.+) FROM user")
fmt.Println(errDb)
defer rs.Close()
for rs.Next() {
u := UserPublic{
Id: 0,Name: "",FirstSurname: "",SecondSurname: "",Email: "",BirthDate: "",IdentityNumber: "",ClinicalNumber: "",IdInsuranceCompany: 0,Card: "",IdClient: 0,PhoneNumber: "",Role: 0,DateCreated: "",}
err := rs.Scan(&u.Id,&u.Name,&u.FirstSurname,&u.SecondSurname,&u.Email,&u.BirthDate,&u.IdentityNumber,&u.ClinicalNumber,&u.Card,&u.PhoneNumber,&u.Role,&u.DateCreated)
if err != nil {
fmt.Println("got scan error:",err)
break
}
}
id,err := s.GetList(int(user.IdClient))
assert.NotNil(t,err)
assert.Nil(t,id)
})
}
我得到的错误是:
使用 args [] 调用 Query 'SELECT (.+) FROM user',不是预期的,下一个预期是: ExpectedPrepare => 预期 Prepare 语句:
- 匹配 sql: 'SELECT (.+) FROM user'
知道错误可能在哪里吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。