8

I am trying to unit test methods that use type *gorm.DB and am curious how to properly define an interface that will enable me to test without hitting a db.

Here is a small example of what I want to do:

type DBProxy interface {
    Create(values interface{}) *DBProxy
    Update(values interface{}) *DBProxy
}

type TestDB struct{}

func (t *TestDB) Create(values interface{}) *TestDB {
    return t
}

func (t *TestDB) Update(values interface{}) *TestDB {
    return t
}

func Connect() DBProxy {
    return &TestDB{}
}

Which results in:

cannot use TestDB literal (type *TestDB) as type DBProxy in return argument:
    *TestDB does not implement DBProxy (wrong type for Create method)
            have Create(interface {}) *TestDB
            want Create(interface {}) *DBProxy

Any help would be appreciated!


UPDATE

Here is my actual application code:

package database

import (
    "log"
    "os"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

type DBProxy interface {
    Create(values interface{}) DBProxy
    Update(values interface{}) DBProxy
}

func Connect() DBProxy {
    databaseUrl := os.Getenv("DATABASE_URL")

    db, err := gorm.Open("postgres", databaseUrl)

    if err != nil {
        log.Fatal(err)
    }

    return db
}

Which results in:

cannot use db (type *gorm.DB) as type DBProxy in return argument:
    *gorm.DB does not implement DBProxy (wrong type for Create method)
            have Create(interface {}) *gorm.DB
            want Create(interface {}) DBProxy

1 Answer 1

1

TestDB methods must return *DBProxy to implement DBProxy

func (t *TestDB) Create(values interface{}) *DBProxy {
    return t
}
func (t *TestDB) Update(values interface{}) *DBProxy {
    return t
}

later you will need to assert CreatedDBProxy.(TestDB)

1
  • Thanks for the response. I am still a little confused. My goal is to create an interface for gorm.DB in order to use a mock in a unit test. Since I don't have control over what gorm.DB methods return, I am unsure of how to correctly define the interface. Commented Apr 23, 2016 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.