首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法将我选择的数据插入到go-sqlmock命令中。

无法将我选择的数据插入到go-sqlmock命令中。
EN

Stack Overflow用户
提问于 2022-11-05 10:48:37
回答 1查看 55关注 0票数 0

尝试执行api- test,测试调用mysql SELECT命令,然后执行INSERT命令,SELECT命令可以工作,但我无法将数据插入到INSERT命令中,但是,如果我不尝试“插入我选择的任何数据”,则INSERT命令可以工作。

代码语言:javascript
复制
func Test_CreateProject(t *testing.T) {
   db, mock, err := sqlmock.New()
   if err != nil {
      t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
   }
   defer db.Close()

   gormDB, err := gorm.Open(mysql.New(mysql.Config{
      Conn: db,
      SkipInitializeWithVersion: true,
   }), &gorm.Config{})
   if err != nil {
      panic(err) // Error here
   }

   var (
      userID             = uint(1)
      userName           = "Jon"
      userUsername       = "johnny"
      userEmail          = "email@email.com"
      userAdministrator  = true
   )

   mock.ExpectQuery("SELECT(.*)").
      WillReturnRows(sqlmock.NewRows([]string{"id", "name", "username", "email", "administrator"}).
      AddRow(userID, userName, userUsername, userEmail, userAdministrator))

   // insert
   mock.ExpectBegin()
   mock.ExpectExec("INSERT INTO projects\\(name, description\\)").
      WithArgs("name", "description").
      WillReturnResult(&result{insertID:int64(1),rowsAffected:int64(1)})
   fmt.Println(mock.ExpectationsWereMet())
   mock.ExpectCommit()

   r := mux.NewRouter()
   r.HandleFunc("/project", CreateProject(gormDB)).Methods("POST")
   ts := httptest.NewServer(r)
   defer ts.Close()
   apitest.New().
      Debug().
      Handler(r).
      Post("/project").
      //Body(fmt.Sprintf(`{"name": "%s", "description": %s}`, name, description)).
      Expect(t).
      //Body(`{"CreatedAt":"0001-01-01T00:00:00Z","UpdatedAt":"0001-01-01T00:00:00Z","DeletedAt":null,"ID":1,"name":"Valshlid","description":"Rand byggður kassi við Hlidarenda i RVK"}`).
      Status(http.StatusOK).
      End()
}
代码语言:javascript
复制
func (project *Project) CreateProject(db *gorm.DB) *error.ErrorResp {
    if err := db.Create(&project).Error; err != nil {
        errResponse := error.New(error.WithDetails(err))
        return errResponse
    }

    return nil
}
代码语言:javascript
复制
mysql> desc projects;
+-------------+-----------------+------+-----+---------+----------------+
| Field       | Type            | Null | Key | Default | Extra          |
+-------------+-----------------+------+-----+---------+----------------+
| id          | bigint unsigned | NO   | PRI | NULL    | auto_increment |
| created_at  | datetime(3)     | YES  |     | NULL    |                |
| updated_at  | datetime(3)     | YES  |     | NULL    |                |
| deleted_at  | datetime(3)     | YES  | MUL | NULL    |                |
| name        | varchar(191)    | YES  | UNI | NULL    |                |
| description | longtext        | YES  |     | NULL    |                |
+-------------+-----------------+------+-----+---------+----------------+
代码语言:javascript
复制
ExecQuery: could not match actual sql: "INSERT INTO `projects` (`created_at`,`updated_at`,`deleted_at`,`name`,`description`) VALUES (?,?,?,?,?)" with expected regexp "INSERT INTO projects\(name, description\)"; call to Rollback transaction, was not expected, next expectation is: %!s(PANIC=String method: runtime error: invalid memory address or nil pointer dereference)
[0.098ms] [rows:0] INSERT INTO `projects` (`created_at`,`updated_at`,`deleted_at`,`name`,`description`) VALUES ('2022-11-05 10:30:34.37','2022-11-05 10:30:34.37',NULL,'','')

<---------- final response
HTTP/1.1 500 Internal Server Error
Connection: close
Content-Type: application/json; charset=UTF-8

{"Err":{"code":500,"status":"Internal Server Error","message":"","details":["ExecQuery: could not match actual sql: \"INSERT INTO `projects` (`created_at`,`updated_at`,`deleted_at`,`name`,`description`) VALUES (?,?,?,?,?)\" with expected regexp \"INSERT INTO projects\\(name, description\\)\"; call to Rollback transaction, was not expected, next expectation is: %!s(PANIC=String method: runtime error: invalid memory address or nil pointer dereference)"]}}

    assert.go:105:
            Error Trace:    assert.go:259
                                        assert.go:89
                                        assert.go:78
                                        apitest.go:1043
                                        apitest.go:880
                                        apitest.go:687
                                        projectcontroller_test.go:206
            Error:          Not equal:
                            expected: 200
                            actual  : 500
            Test:           Test_CreateProject
Duration: 961.959µs

--- FAIL: Test_CreateProject (0.00s)
FAIL
FAIL    timeclock/controllers   0.205s
FAIL
EN

回答 1

Stack Overflow用户

发布于 2022-11-15 08:32:26

您应该使用"mock.ExpectPrepare“而不是"mock.ExpectExec”。你不确定你试过吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74327062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档