0

I use gin framework and ORM framework gorm to develop web application.The DB is Mysql.

Every unit test will produce dirty data. So I use AfterCreate hook to record table name and the id when create an object.Then delete dirty data by traversing the list of record.

I need to add hook function to every model like:

func (f User) AfterCreate(tx *gorm.DB) (err error) {
    DBTestAddRecord([2]interface{}{f.ID, &User{}})
    return
}

It can work but very annoying. Is there any other solution?

Eklavya
  • 17,618
  • 4
  • 28
  • 57
Kobshobe
  • 89
  • 1
  • 6
  • 1
    If you're unit testing. You should be mocking out the connection to the database so that your tests never make any changes. I'd have a look at resources about unit testing in general if you're unfamiliar. – James May 11 '21 at 10:57
  • Have a look at [How to unit test a gorm application with sqlmock](https://betterprogramming.pub/how-to-unit-test-a-gorm-application-with-sqlmock-97ee73e36526). By mocking the database your tests run faster and you can easily clean up after yourself. – Ezequiel Muns May 11 '21 at 14:16

0 Answers0