Trying to execute an api-test, test calls a mysql gorm SELECT
command, then subsequently executes an INSERT
command, the SELECT
command works, but I have not been able to insert data at my choice into the INSERT
command, however the INSERT
command works if I try not to `INSERT any data at my choice.
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()
}
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
}
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 | |
+-------------+-----------------+------+-----+---------+----------------+
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