簡體   English   中英

Golang gorm 嘲弄

[英]Golang gorm mocking

我在我的項目中使用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)
    })
}

對於單元測試,模擬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)
    }
}

我在我的項目中使用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)
    })
}

如果您使用的是干凈的架構,只需模擬您的存儲庫,它會好得多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM