首頁 >後端開發 >Golang >如何有效模擬Golang中的函數?

如何有效模擬Golang中的函數?

Linda Hamilton
Linda Hamilton原創
2024-12-07 07:51:17575瀏覽

How Can I Effectively Mock Functions in Golang?

Golang 中的模擬函數

在 Golang 中,不直接支援在具體類型上宣告的模擬函數。但是,有多種策略可以實現類似的功能。

函數值

可以模擬函數值,包括變數、結構體欄位或參數。請考慮以下內容:

var Fn = func() { ... }

type S struct {
    Fn func()
}

func F(Fn func())

所有這些實例中的 Fn 都是可模擬的。

介面

類比介面是首選選項。建立一個代表目標函數方法的介面:

type ProductRepository interface {
    GetProductById(DB *sql.DB, ID int) (p Product, err error)
}

實作此介面的真實版本和模擬版本:

// Real implementation
type ProductStore struct{}

func (ProductStore) GetProductById(DB *sql.DB, ID int) (p Product, err error) {
    // ...
}

// Mock implementation
type ProductRepositoryMock struct {}

func (ProductRepositoryMock) GetProductById(DB *sql.DB, ID int) (p Product, err error) {
    // ...
}

現在可以傳遞依賴ProductRepository 的程式碼用於生產使用的真實實現和用於測試的模擬實現。

接口模仿

或者,定義一個模仿*sql.DB 方法的接口,然後使用該接口類型作為函數的參數類型:

type DBIface interface {
    Query(query string, args ...interface{}) (*sql.Rows, error)
    // ...
}

type DBMock struct {}

func (DBMock) Query(query string, args ...interface{}) (*sql.Rows, error) {
    // ...
}

func GetProductByName(DB DBIface, name string) (p Product, err error) {
    // ...
}

這使得DB 參數可模擬。

以上是如何有效模擬Golang中的函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn