我是Golang的新手。我试图使用go-sqlmock模拟我的postgres,但我得到了这个错误
{“time”:“2023-10- 01 T18:07:05.495811+03:00”,“level”:“FATAL”,“prefix”:“-",“file”:“repository.go”,“line”:“15”,“message”:“执行对ExecQuery 'insert into public'的查询调用时出错。“(“Id”,“Name”,“Email”)值($1,$2,$3)',带args [{Name:Ordinal:1 Value:e918 b 0 bc-76 f3 -4380-a1 fb-a14 ca 5a 08 fc 3} {姓名:序号:2数值:Jon Snow} {姓名:序号:3数值:email protected(https://stackoverflow.com/cdn-cgi/l/email-protection)}],不期望,下一个期望是:ExpectedBegin =>期望数据库事务Begin”}
我试图测试的方法是添加到数据库用户。我谷歌这个错误,但不能的东西。为什么我得到这个错误?
myTest file
var user = &User{
Id: userIdUuid,
Name: "Jon Snow",
Email: "[email protected]",
}
func TestUserRepository_create_whenEverythingIsOk(t *testing.T) {
t.Parallel()
//arrange
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expoected when opening a stub database connection", err)
}
defer db.Close()
mock.ExpectBegin()
mock.ExpectExec(`insert into public."Users" ("Id", "Name", "Email") values ($1,$2,$3)`).WithArgs(user.Id, user.Name, user.Email)
mock.ExpectCommit()
repository := NewUserRepository(db)
if err := repository.Create(*user); err != nil {
t.Errorf("error was not expected while inserting user: %s", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
my repository func
func (repo *userRepository) Create(user User) (err error) {
query := `insert into public."Users" ("Id", "Name", "Email") values ($1,$2,$3)`
_, err := repo.db.Exec(query, user.Id, user.Name, user.Email)
if err != nil {
log.Fatalf("An error occurred while executing the query %v", err)
}
return
}
my db initilization
func NewDb() (*sql.DB, error) {
var config configs.Config
if err := viper.Unmarshal(&config); err != nil {
fmt.Println(err)
return nil, err
}
db, err := sql.Open("postgres", fmt.Sprintf("%s", config.PostgresConnection[0]["connectionstring"]))
if err != nil {
panic("failed to connect database")
}
if err := db.Ping(); err != nil {
log.Fatalf("unable to reach database: %v", err)
}
return db, nil
}
func Installer(e *echo.Echo) {
db, err := db_helper.NewDb()
if err != nil {
panic(err)
}
userRepo := entities.NewUserRepository(db)
userService := entities.NewUserService(userRepo)
controller := entities.NewUserHandler(userService)
e.GET("api/user/:id", controller.GetById)
e.POST("api/user", controller.Create)
e.GET("api/user", controller.GetUsers)
}
字符串
1条答案
按热度按时间iugsix8n1#
我找到了答案。
字符串
这个方法需要一个transaction。我没有使用transaction,所以会出现错误。我删除了这几行,就这样完成了。