0

我正在对一项服务执行单元测试,其中验证了请求 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}

希望我的解释是有道理的,在我的代码所依据的文章中没有讨论单元测试。

4

1 回答 1

0

我设法模拟了我的加密包,然后在我的测试中模拟,解决方案相当冗长,但我希望它在未来对其他人有所帮助。我还在学习 Go,所以有些术语可能不正确(呵呵)

首先创建一个包,你的哈希逻辑将被创建,更多信息在这里,我使用mockgen来创建我的模拟,所以我在我的界面中添加了注释

//go:generate mockgen -destination=../mocks/crypto/mockCrypto.go -package=crypto auth-server/crypto AppCrypto
type AppCrypto interface {
    HashAndSalt(pwd []byte) (string, *errs.AppError)
    ComparePasswords(hashedPwd string, plainPwd []byte) bool
}


type DefaultAppCrypto struct {
}

// HashAndSalt Hashes a given string
func (d DefaultAppCrypto) HashAndSalt(pwd []byte) (string, *errs.AppError) {

    hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
    if err != nil {
        return "", errs.NewUnexpectedError("An unexpected error ocurred while hashing the password" + err.Error())
    }
    return string(hash), nil
}

func (d DefaultAppCrypto) ComparePasswords(hashedPwd string, plainPwd []byte) bool { 
    byteHash := []byte(hashedPwd)
    err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
    if err != nil {
        return false
    }

    return true
}

我正在遵循您在此 Udemy 课程中学到的六边形架构强烈推荐),因此我正在创建一个用于注册新用户的帐户服务,该服务需要一个用于访问其结构中数据层的存储库,所以如果我们要注入然后我们就可以在测试中模拟它的实现。

这里会省略一些代码,主要是实现:

type AccountService interface {
    RegisterAccount(dto.RegisterRequest) (*dto.RegisterResponse, *errs.AppError)
}

type DefaultAccountService struct {
    repo   domain.AccountRepository
    crypto crypto.AppCrypto
}

// More code here

func NewAccountService(repo domain.AccountRepository, crypto crypto.AppCrypto) DefaultAccountService {
    return DefaultAccountService{repo, crypto}
}

现在我们应该能够模拟这个包,所以这样的事情会起作用。

var mockRepo *domain.MockAccountRepository
var mockCrypto *crypto.MockAppCrypto
var ctrl gomock.Controller
var service AccountService

func setup(t *testing.T) func() {
    ctrl := gomock.NewController(t)
    mockRepo = domain.NewMockAccountRepository(ctrl)
    mockCrypto = crypto.NewMockAppCrypto(ctrl)
    service = NewAccountService(mockRepo, mockCrypto)

    return func() {
        service = nil
        defer ctrl.Finish()
    }
}

func Test_should_create_new_account(t *testing.T) {
    // Arrange
    teardown := setup(t)
    defer teardown()

    cryptoService := realCrypto.DefaultAppCrypto{}

    password := "securepassword"
    hashedpassword, err := cryptoService.HashAndSalt([]byte(password))

    request := dto.RegisterRequest{
        Email:    "test@test.com",
        Password: password,
        RoleID:   1,
    }

    account := realDomain.Account{
        Email:    request.Email,
        Password: hashedpassword,
        RoleID:   request.RoleID,
    }

    accountWithID := account
    accountWithID.AccountID = 1

    // ** MOCK THE DATA LAYER IMPLEMENTATION
    mockRepo.EXPECT().Create(account).Return(&accountWithID, nil)
    // ** MOCK THE CRYPTO PACKAGE's HashAndSalt
    mockCrypto.EXPECT().HashAndSalt([]byte(password)).Return(hashedpassword, 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")
    }

}

最初我的加密包只有散列所需的功能,但我被迫将它们包含在 a 中struct,所以如果有更多经验的人知道以帐户服务将使用模拟实现的方式模拟散列函数的方法将是很好,因为代码会简单得多。

于 2021-02-08T00:58:00.807 回答