gpt4 book ai didi

go - 通过担架/验证模拟,不同的返回参数

转载 作者:行者123 更新时间:2023-12-01 22:15:00 25 4
gpt4 key购买 nike

下面的函数描述了如何使用testify进行模拟。 args.Bool(0)args.Error(1)是模拟的位置返回值。

func (m *MyMockedObject) DoSomething(number int) (bool, error) {

args := m.Called(number)
return args.Bool(0), args.Error(1)

}

是否可以返回 args.Int()args.Bool()args.String()以外的其他内容?如果我需要返回 int64或自定义 struct怎么办?有没有方法或者我缺少什么?

例如:
func (m *someMock) doStuff(p *sql.DB, id int) (res int64, err error)

最佳答案

是的,可以通过使用args.Get和类型断言来实现。

docs:

// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion:
//
// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine)

因此,您的示例将是:

func (m *someMock) doStuff(p *sql.DB, id int) (res int64, err error) {
args := m.Called(number)
return args.Get(0).(int64), args.Error(1)
}

另外,如果您的返回值是一个指针(例如,指向struct的指针),则应在执行类型声明之前检查其是否为nil。

关于go - 通过担架/验证模拟,不同的返回参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60916779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com