3 ms·
Writing Good Unit Tests; Don't Mock Database Connections
- Supermancho 6y ago> Assuming the saveUserInDB function is just making a SQL query, it probably doesn’t need a unit test at all It's possible I don't know Go well enough. func (mdb *mockDB) Exec(query string, args ...interface{}) (sql.Result, error) { return nil, nil } You're specifically returning nils, which is different than the native implementation from https://golang.org/pkg/database/sql/#DB.Exec https://golang.org/pkg/database/sql/#DB.Exec I would write a test using a mock and asserting the fact that it neither deals with an error nor does it return anything useful (no Result).
- cratermoon 6y agoThis function takes a `query` of type `string` and a variable-length list of `args` of type `interface{}`, which is anything, (real implementations would have code to determine if the type is correct), and returns `(sql.Result, error)` In this mock version, he's returning a nil for both. I take this as example code, because if the results are actually checked in the test, then the first result would have to be non-nil if the error was nil. It doesn't really matter, because the author is saying not to do this.
- MichaelRazum 6y agoWhy don't test against a local SQLlite Database or a Database that is created on the fly. I think you should definitely test the Database logic.
- gravypod 6y agoIn my opinion you should only test the functionality of the code that you're "talking about". Ideally you'll have some component that exposes a `GetX(id)`, `SaveX(x)`, `FindX(WithName(foobar))` or something. That code should be tested against a mock of the DB. Everything else should use a mock/fake of that API. This has many reasons why you'd want to do it. Many people stick to "performance" but I think that's the weakest reason. Ideally if you change some code and break something you want the method name of a failed test to tell you what's wrong. If you change some ORM code and 100% of your tests fail, is that helpful? Compared to the case where you change the ORM code and the unit tests testing the ORM code fail?
- lupire 6y agoSQLite is a fake for the remote database. > you change some ORM code and 100% of your tests fail, is that helpful? Yes. It shows what depends on the ORM behavior. Of course you need to be smart about finding the root cause.
- DanielJohn 6y agoNot testing data access can give developers a false sense of security when pushing changes to production. Docker images are fast enough to spin up during setup/teardown and your future self will likely thank you for running a proper integration test.