简体   繁体   中英

Mocking via stretchr/testify, different return args

Function below describes how to mock using testify. args.Bool(0) , args.Error(1) are mocked positional return values.

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

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

}

Is it possible to return anything other than args.Int() , args.Bool() , args.String() ? What if I need to return int64 , or a custom struct . Is there a method or am I missing something?

For example:

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

Yes, it is possible by using args.Get and type assertion.

From the 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)

So, your example would be:

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)
}

Additionaly, if your return value is a pointer (eg pointer to struct), you should check if it is nil before performing type assertion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM