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 (e.g. pointer to struct), you should check if it is nil before performing type assertion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With