登录
首页 >  Golang >  Go问答

使用 Go-SQL 模拟 GORM 进行 PostgreSQL 插入

来源:stackoverflow

时间:2024-02-23 14:12:24 280浏览 收藏

golang学习网今天将给大家带来《使用 Go-SQL 模拟 GORM 进行 PostgreSQL 插入》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在使用 gorm 和 postgresql 驱动程序。我尝试使用 go-sqlmock 模拟数据库插入:

type test struct {
    firstname string `json:"first_name"`
}

func (db *db) createtest() (*test, error) {
    test := test{"c"}
    if result := db.create(&test); result.error != nil {
        return nil, result.error
    }

    return &test, nil
}


func testcreateuser(t *testing.t) {
    _, mock, _ := sqlmock.newwithdsn("sqlmock_db_0")

    mockedgorm, _ := gorm.open("sqlmock", "sqlmock_db_0")
    defer mockedgorm.close()
    mydb := &db{mockedgorm}

    mock.expectexec("insert into test").withargs("c").willreturnresult(sqlmock.newresult(1, 1))
    mydb.exec("insert into test(first_name) values (?)", "c")


    if _, err := mydb.createtest(); err != nil {
        t.errorf("error was not expected: %s", err)
    }

    if err := mock.expectationsweremet(); err != nil {
        t.errorf("there were unfulfilled expectations: %s", err)
    }
}

不幸的是,这给了我一个错误:

error was not expected: all expectations were already fulfilled, call to database transaction Begin was not expected

如何正确使用 gorm、postgresql 和 sql-mock 测试插入?


解决方案


我的代码存在一些问题:

1) 正如 @flimzy 正确指出的那样,必须有一个 expectbegin() (和 expectcommit())语句。如果打开 gorm 调试器来显示 gorm 正在做什么,这一点会变得更加明显。

2) expectexec("insert into test").withargs("c") 显然不匹配 mydb.exec("insert into test(first_name) values (?)", "c") p>

3)必须转义该语句,因为 go-sqlmock 采用正则表达式,这里 go 的 https://godoc.org/regexp#QuoteMeta 就派上用场了。

工作代码:

mock.ExpectBegin()
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO \"tests\" (\"first_name\") VALUES (?)")).WithArgs("c").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()

终于介绍完啦!小伙伴们,这篇关于《使用 Go-SQL 模拟 GORM 进行 PostgreSQL 插入》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>