2016-04-23 172 views
3

我試圖使用類型*gorm.DB和很好奇如何正確定義一個接口,使我沒有碰到一個分貝測試單元測試方法。如何正確定義一個gorm db接口?

這裏是我想要做的一個小例子:

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{} 
} 

導致:

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 

任何幫助,將不勝感激!


UPDATE

這裏是我的實際應用程序代碼:

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 
} 

導致:

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

TestDB方法必須返回*DBProxy實施DBProxy

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

後,你將需要斷言CreatedDBProxy.(TestDB)

+0

感謝您的答覆。我仍然有點困惑。我的目標是創建一個'gorm.DB'的接口,以便在單元測試中使用模擬。 因爲我無法控制'gorm.DB'方法返回什麼,所以我不確定如何正確定義接口。 – astephenb