mockery
mockery copied to clipboard
Obtain the arguments of the function call on the mocked variable
Is there a way to obtain the arguments on the function call of the mocked variable? This soooo helps out during testing.
One way to do it (probably not the prettiest):
myArg := myMock.Calls[len(myMock.Calls)-1].Arguments[0].(*MyArgumentType)
Update: I created a helper function:
func LastCall(expectedCall *mock.Call) *mock.Call {
calls := expectedCall.Parent.Calls
for i := len(calls) - 1; i >= 0; i-- {
if expectedCall.Method != calls[i].Method {
continue
}
_, diff := expectedCall.Arguments.Diff(calls[i].Arguments)
if diff == 0 {
return &calls[i]
}
}
return nil
}
And use it like this:
myFunctionCall := myMock.On("MyFunction", mock.Anything).Return("the-result")
....
arg := LastCall(myFunctionCall).Arguments.Get(0).(string)
You can use the .Run
method provided by testify
, or you can use the .RunAndReturn
method from the expecter structs that will call the function you provide with the arguments that were used in the call.