I built the following 2 interfaces in order to make my code, which makes calls to the sql package, testable:
type Database interface {
Close() error
Query(string, ...interface{}) (DatabaseRows, error)
}
type DatabaseRows interface {
Close() error
Next() bool
Scan(...interface{}) error
}
and the actual code which I want to test is:
func getDatabase(connectionString string) (db Database, err error) {
if db , err = sql.Open("mysql", connectionString); err != nil {
glog.V(0).Infof("Error %s", err)
}
return
}
But this fails to compile:
*sql.DB does not implement Database (wrong type for Query method)
have Query(string, ...interface {}) (*sql.Rows, error)
want Query(string, ...interface {}) (DatabaseRows, error)
If I understand it correctly, it's telling me that it can't return a *Row where a DatabaseRow is expected, even though Rows struct in is implementing all 3 functions that I declared in DatabaseRows interface.
Why doesn't compiler make that association?
*sql.Rowsdoes implementDatabaseRows. The problem is that the method signatures are different, resulting in different method sets.