简体   繁体   中英

How to mock DB for unit tests

I have UserRepo like this:

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. But how do I mock this method for unit tests? And in Gorm how to mock for other databases queries?

Mocking in Go Is all about Go Interfaces. 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. You might also want to use Popular mocking/testing frameworks like go-mock or testify for creating mocks.

Now, you will have to implement a factory method such that it will return mockStruct depending on the condition. 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,
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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