DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.06k stars 408 forks source link

can i get both non-nil rows and error at the same time? #173

Closed justinling89 closed 5 years ago

justinling89 commented 5 years ago

can i get both non-nil rows and error at the same time?i use sqlmock like this:

rows := NewRows([]string{"id", "title"}). AddRow(1, "one"). AddRow(2, "two") mock.ExpectQuery("SELECT FROM users").WillReturnRows(rows).WillReturnError(&os.PathError{Path:"/"}) resultRows, resultErr := db.Query("SELECT FROM users")

i want to get non-nil resultRows and non-nil resultErr at the same time,but i found i can only get non-nil resultErr but the resultRows is always nil,why?

justinling89 commented 5 years ago

@AlekSi @bbigras @gliptak @mrroman Please pay attention to this question ,thanks!

l3pp4rd commented 5 years ago

In golang, you cannot expect non nil rows if there is an error, because the first check you must do is for error after you get a result. If your code expects non nil rows and an error, then something is wrong with your understanding of go language.

If function in go returns an error and any number of other values, you always must check the error first, because there are no guaranties that any of those values will be valid.

Sqlmock may return just nil for rows if there is an error, because in such case it will not matter if there are rows due to error.