Golang gorm 嘲讽

Pum*_*eed 7 database testing mocking go go-gorm

我在我的项目中使用gorm。我可以在没有数据库连接的情况下模拟这个数据库 orm 进行测试吗?我们有 CI 工具的问题,我没有数据库或数据库有足够的数据进行测试。另一方面,我不想在每次测试时都设置一个数据库,因为在这些情况下,CI 工具每次都会创建一个容器来运行测试。

测试数据库相关方法的最佳方法是什么?我在我的解决方案中使用依赖注入,因此很容易用模拟数据库替换数据库。但是gorm 有很多与orm 相关的功能。

这是一个处理程序,例如:

func tokenIntrospectionHandler(db *gorm.DB) http.HandlerFunc {
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        defer req.Body.Close()
        token := req.FormValue("token")
        var resp Response
        json.NewEncoder(w).Encode(resp)
    })
}
Run Code Online (Sandbox Code Playgroud)

ger*_*nio 4

对于单元测试,这看起来非常适合模拟gorm.DB: https: //github.com/DATA-DOG/go-sqlmock

这是他们网站上的一个例子。您只需创建模拟,然后创建数据库,设置方法调用的期望,然后在测试中运行代码,最后检查是否满足期望。


// a successful case
func TestShouldUpdateStats(t *testing.T) {
    db, mock, err := sqlmock.New()
    if err != nil {
        t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
    }
    defer db.Close()

    mock.ExpectBegin()
    mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
    mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
    mock.ExpectCommit()

    // now we execute our method
    if err = recordStats(db, 2, 3); err != nil {
        t.Errorf("error was not expected while updating stats: %s", err)
    }

    // we make sure that all expectations were met
    if err := mock.ExpectationsWereMet(); err != nil {
        t.Errorf("there were unfulfilled expectations: %s", err)
    }
}
Run Code Online (Sandbox Code Playgroud)