簡體   English   中英

通過拉伸器/作證模擬,不同的返回參數

[英]Mocking via stretchr/testify, different return args

下面的函數描述了如何使用 testify 進行模擬。 args.Bool(0) , args.Error(1)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和類型斷言。

文檔

// 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。

暫無
暫無

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

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