go - 如何正确定义 gorm 数据库接口(interface)?

标签 go go-gorm

我正在尝试对使用 *gorm.DB 类型的方法进行单元测试,并且很好奇如何正确定义一个接口(interface),使我能够在不访问数据库的情况下进行测试。

这是我想做的一个小例子:

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

如有任何帮助,我们将不胜感激!


更新

这是我的实际应用程序代码:

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

最佳答案

TestDB 方法必须返回 *DBProxy 来实现 DBProxy

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

稍后您将需要断言 CreatedDBProxy.(TestDB)

关于go - 如何正确定义 gorm 数据库接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816553/

相关文章:

jsonb - 使用 GORM for 运算符查询 JSONB 列

json - 在 Go 中为导入的结构设置标签

go - DropColumn 如果存在于 GORM 中

postgresql - 将 gorm.Model 字段集成到 protobuf 定义中

unit-testing - Uber Cadence 事件的单元测试上下文

c++ - 为什么我的程序在分配更多线程的情况下执行时间更长?

go - 在 gorm 中使用 'FROM' 中的子查询

git - 如何在将 vendor 目录 checkin 版本控制时管理 Go 依赖项?

go - 如何停止被进程启动的外部 I/O 阻塞的 goroutine?

arrays - 如何将 []string 转换为 ...string