我正在尝试模拟以下功能。我正在努力让它测试 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'
知道错误可能在哪里吗?