通过拉伸器/作证模拟,不同的返回参数

下面的函数描述了如何使用 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)


繁花如伊
浏览 127回答 1
1回答

12345678_0001

是的,可以通过使用args.Get和类型断言来实现。从文档:// 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(p, id)    return args.Get(0).(int64), args.Error(1)}另外,如果您的返回值是一个指针(例如指向结构的指针),您应该在执行类型断言之前检查它是否为 nil。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go