Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly define a gorm db interface?

Tags:

go

go-gorm

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
like image 723
a-b-r-o-w-n Avatar asked Apr 23 '16 21:04

a-b-r-o-w-n


1 Answers

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)

like image 107
Uvelichitel Avatar answered Sep 28 '22 07:09

Uvelichitel