It will be great if the DB type can be turned into an interface, so users can mock the interface in tests as appropriate. Otherwise we will need to do wrappers etc. to achieve this, which isn't optimal.
Were there any reasons why it started as a struct?
Thanks!
Will be so much better to test integration with gormif we have a interface to mock ( I use testify to do this). @jinzhu I think that using go-testdb don't resolve the problem because by using it I'm testing gormagain every time, seeing if it return the correct query or result and this is not the best way to test.
Mocking a interface to gorm we can expected the right methods on gormto be called with the right params, trusting that the gorm library is already well tested.
I tried to do this but because gorm have a chainable API, I could not mock the return of the methods, because they return the concrete implementation gorm.DB, breaking a test that requires more then one method to be called in a chain.
I forked the project to create a common interface, but unfortunatly will be introduce a breaking change to the library. Do we have a roadmap for gorm?
cc @danqing
Hi @alvarowolfx
I could accept some break changes in the v1.0 release if it is valuable, refer: https://github.com/jinzhu/gorm/pull/794
I am thinking you could go-testdb to mock some queries for testing. but really suggest you use the real database that you are using in production for testing.
@danqing @alvarowolfx @sunfmin @levinalex
I use sqlmock to mock-test GORM queries. Example is here, search e.g. testUserSelectAll.
First I tried go-testdb and custom gorm.DB wrapper to interface, but current solution with sqlmock is the simplest.
There are other use case beyond testing where providing a DB interface would be useful. For example, I'm currently working on a project that provides a generic storage interface. It would be useful for that interface to have a StorageEngine() interface{} method, however I can't do that currently due to the lack of a DB interface.
@jinzhu: Could providing a DB interface be reconsidered given alternate use cases beyond testing?
I'm also leaning towards having a DB interface, which could make write unit tests for the code where used gorm functions become much easier. Ideally, we should not care about the internal implementation inside gorm or which SQL query has been executed, instead, we should only care about the response we expected from gorm.
@jinzhu Really suggest you consider this. Appreciate it.
Most helpful comment
I'm also leaning towards having a
DBinterface, which could make write unit tests for the code where used gorm functions become much easier. Ideally, we should not care about the internal implementation insidegormor which SQL query has been executed, instead, we should only care about the response we expected fromgorm.@jinzhu Really suggest you consider this. Appreciate it.