我正在对一项服务执行单元测试,其中验证了请求 dto,并使用 Go 的Bcrypt 包对用户密码进行了哈希处理,然后再将其传递到存储库以插入数据库。
我不知道我的模拟函数应该如何返回一个应该与服务的散列匹配的虚拟响应。
func Test_should_create_new_account(t *testing.T) {
// Arrange
teardown := setup(t)
defer teardown()
// ** Focus here **
hashedpassword, err := AppCrypto.HashAndSalt([]byte("securepassword"))
request := dto.RegisterRequest{
Email: "test@test.com",
Password: "securepassword",
RoleID: 1,
}
account := realDomain.Account{
Email: request.Email,
Password: hashedpassword,
RoleID: request.RoleID,
}
accountWithID := account
accountWithID.AccountID = 1
mockRepo.EXPECT().Create(account).Return(&accountWithID, nil)
// Act
res, err := service.RegisterAccount(request)
// Assert
if err != nil {
t.Error("Failed while creating account")
}
if !res.Created {
t.Error("Failed while creating account")
}
}
HashAndSalt
简单地散列给定的字符串。
// HashAndSalt Hashes a given string
func HashAndSalt(pwd []byte) (string, *errs.AppError) {
// Use GenerateFromPassword to hash & salt pwd.
// MinCost is just an integer constant provided by the bcrypt
// package along with DefaultCost & MaxCost.
// The cost can be any value you want provided it isn't lower
// than the MinCost (4)
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
return "", errs.NewUnexpectedError("An unexpected error ocurred while hashing the password" + err.Error())
} // GenerateFromPassword returns a byte slice so we need to
// convert the bytes to a string and return it
return string(hash), nil
}
这是服务的RegisterAccount
func (d DefaultAccountService) RegisterAccount(request dto.RegisterRequest) (*dto.RegisterResponse, *errs.AppError) {
err := request.Validate()
if err != nil {
return nil, err
}
// Hash the request's password
hashedpassword, err := AppCrypto.HashAndSalt([]byte(request.Password))
if err != nil {
return nil, err
}
// Assign the hashed password to the request obj
request.Password = hashedpassword
a := request.ToDomainObject()
_, err = d.repo.Create(a)
if err != nil {
return nil, err
}
response := dto.RegisterResponse{
Created: true,
}
return &response, nil
}
这是抛出的错误,请注意模拟请求与给定请求不匹配的want
和块。got
accountService.go:34: Unexpected call to *domain.MockAccountRepository.Create([{0 test@test.com 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}]) at /home/dio/Documents/Code/go-beex-backend/auth-server/mocks/domain/accountRepositoryDB.go:40 because:
expected call at /home/dio/Documents/Code/go-beex-backend/auth-server/service/accountService_test.go:52 doesn't match the argument at index 0.
Got: {0 test@test.com 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}
Want: is equal to {0 test@test.com 1 $2a$04$Bah8tCOzf7Z9Suw55DfyHOvnsBbXLyJEWV8QZ.owCBUOxxomAuEM2 false}
希望我的解释是有道理的,在我的代码所依据的文章中没有讨论单元测试。