mockery icon indicating copy to clipboard operation
mockery copied to clipboard

Obtain the arguments of the function call on the mocked variable

Open SUMUKHA-PK opened this issue 3 years ago • 1 comments

Is there a way to obtain the arguments on the function call of the mocked variable? This soooo helps out during testing.

SUMUKHA-PK avatar May 03 '21 09:05 SUMUKHA-PK

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)

tidbeck avatar Nov 17 '21 10:11 tidbeck

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.

LandonTClipp avatar May 09 '23 18:05 LandonTClipp