Hey there!
I'm transitioning from Python and Ruby, where we often use monkeypatching to simplify testing. I've noticed that this approach doesn't really apply in Go, so I'm keen to learn best practices for testing here.
I've got a basic API controller that handles new user registration—it processes the payload and then calls a repository to save the data in a database.
What's the best way to test this without involving the actual database? Should I consider using dependency injection to pass in a Repository instance, so I can use a mock for testing?
Thanks in advance for your advice!
type UserCredentials struct {
Email string `json:"email"`
Password string `json:"password"`
}
func RegisterNewUserController(c *gin.Context) {
var user UserCredentials
if err := c.ShouldBindJSON(&user); err != nil {
fmt.Print(err)
c.JSON(400, gin.H{"message": "bad request"})
return
}
new_user := models.User{Email: user.Email, Password: user.Password}
repository, err := repositories.NewUserRepository()
if err != nil {
fmt.Print(err)
c.JSON(500, gin.H{"message": "Sorry dude, we failed you..."})
return
}
user_id, err := repository.SaveUser(&new_user)
if err != nil {
fmt.Print(err)
c.JSON(500, gin.H{"message": "Sorry dude, we failed you..."})
return
}
c.JSON(http.StatusOK, gin.H{"ID": user_id})
}