Mocking via stretchr/testify, different return args
Asked Answered
T

1

7

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)
Tafilelt answered 29/3, 2020 at 15:47 Comment(2)
Go does not support overloading of user-defined functions on the return types nor the arguments. However you can use two functions with different names.Exaggerated
and this is not about overloading it is about testify libraryTafilelt
W
15

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 (e.g. pointer to struct), you should check if it is nil before performing type assertion.

Winding answered 30/3, 2020 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.