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中文网其他相关文章!