I am using gorm in my projects. Can I mock this database orm for testing without database connection? The problem we have CI tools where I don't have database or database with enough data for testing. The other way, I don't want to setup a database for every time I'm testing, because in these cases the CI tool create every time a container just for run the tests.
Whet is the best way for testing database related methods? I am using dependency injection in my solutions so it is easy to replace the database with a mocked database. But the gorm have many orm related function.
This is a handler for example:
func tokenIntrospectionHandler(db *gorm.DB) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
token := req.FormValue("token")
var resp Response
json.NewEncoder(w).Encode(resp)
})
}
for unit tests, this looks pretty good to mock
gorm.DB
: https://github.com/DATA-DOG/go-sqlmockHere's an example from their site. You just creates the mock, then the DB, sets the expectations for the method calls, then run your code under testing and finally check if the expectations are met.