简体   繁体   English

如何模拟 DB 进行单元测试

[英]How to mock DB for unit tests

I have UserRepo like this:我有这样的 UserRepo:

type users struct {
   *gorm.DB
}

func NewMySqlUsersRepository(db *gorm.DB) repository.IUsers {
    return &users{
        DB: db,
    }
}

Corresponding methods implementation对应方法实现

func (r *users) Save(user *domain.User) (*domain.User, *errors.RestErr) {
  err := r.DB.Model(&domain.User{}).Create(&user).Error

  if err != nil {
    logger.Error("error occurred when create user", err)
    return nil, errors.NewInternalServerError(errors.ErrSomethingWentWrong)
  }

  return user, nil
}

For database mock, I am using sqlmock.对于数据库模拟,我使用的是 sqlmock。 But how do I mock this method for unit tests?但是我如何为单元测试模拟这个方法? And in Gorm how to mock for other databases queries?在 Gorm 中如何模拟其他数据库查询?

Mocking in Go Is all about Go Interfaces. Go 中的 Mock 是关于 Go 接口的。 You will have to create an interface for the repository and implement the Interface methods.您必须为存储库创建一个接口并实现接口方法。

type interface IUserRepository{
     save(user *UserModel) (*userModel, Err)
}

Now all you need to do is to create a mock struct along with the user struct.现在您需要做的就是创建一个模拟结构以及用户结构。 Both of these structs will implement IUserRepository.这两个结构都将实现 IUserRepository。 You might also want to use Popular mocking/testing frameworks like go-mock or testify for creating mocks.您可能还想使用流行的模拟/测试框架,如go-mocktestify来创建模拟

Now, you will have to implement a factory method such that it will return mockStruct depending on the condition.现在,您必须实现一个工厂方法,以便它根据条件返回 mockStruct。 You can inject the condition variable with context, env variable, or any other way.您可以使用上下文、环境变量或任何其他方式注入条件变量。

func NewMySqlUsersRepositoryFactory(ctx context.Context, env string, db *gorm.DB) repository.IUsers {
    if env == "test" {
        // This is a mocked struct ...
        return mock.MockUsers{}
    }
     // This is a actual struct... 
    return &users{
        DB: db,
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM