1

I am using the sqlmock library to test with mysql's GORM database. However, I have a statement that requires executing an INSERT command multiple times with the same information, so I add my code snippet

file_test.go - Mock database

func mockDatabase(t *testing.T) *gorm.DB {
    sqlDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
    if err != nil {
        log.Fatalf("[sqlmock new] %s", err)
    }

    mock.ExpectQuery("SELECT VERSION()").
        WithArgs().
        WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow("1"))

    sentencePrepare := mock.ExpectPrepare("^INSERT INTO `TABLE(.+)")
    sentencePrepare.ExpectExec().
        WithArgs("A", "B", "C", "D", "E").
        WillReturnResult(sqlmock.NewResult(1, 1))

    sentence2Prepare := mock.ExpectPrepare("^INSERT INTO `TABLE(.+)")
    sentence2Prepare.ExpectExec().
        WithArgs("A", "B", "C", "D", "E").
        WillReturnResult(sqlmock.NewResult(1, 1))

    db, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB, DriverName: "mysql"}), &gorm.Config{PrepareStmt: true})
    if err != nil {
        t.Fatalf("[gorm open] %s", err)
    }

    return db

}

file create_row.go

func (s Repository) CreateRow(rowInfo RowInfo) (*RowInfo, error) {
    if dbQueryError := s.db.Create(&rowInfo).Error; dbQueryError != nil {
        return nil, dbQueryError
    }
    return &rowInfo, nil
}

file TestRegisterRow.go

for _, item := range dataRow {
    CreateRow(item)
}

The problem is the following: I have three items in "dataRow", the first is executed correctly, but the second generates the error (without more information), even though the data is the same and the statement is also the same

call to ExecQuery 'INSERT INTO TABLE (column1,column2,column3,column4,column5) VALUES (?,?,?,?,?)' with args [{Name: Ordinal:1 Value:A} {Name: Ordinal:2 Value:B} {Name: Ordinal:3 Value:C} {Name: Ordinal:4 Value:D} {Name: Ordinal:5 Value:E}], was not expected, next expectation is: ExpectedPrepare => expecting Prepare statement which: -matches sql: '^INSERT INTO `TABLE(.+)'

Could someone please help me identify why it happens, I have validated several forums and I cannot overcome the error. If necessary I can also change the unit test code so that multiple queries can be executed.

0 Answers0