Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Type-safe return values #427

Closed
jtyers opened this issue Apr 20, 2020 · 3 comments
Closed

Type-safe return values #427

jtyers opened this issue Apr 20, 2020 · 3 comments

Comments

@jtyers
Copy link

jtyers commented Apr 20, 2020

Requested feature
I have recently moved from testify/mockery to using GoMock for generating mocks, and simply having the mock aware of the types of my calls is great.

However, the arguments for Return() are always interface{}. Can gomock generate mocks that Return with types that match the underlying method?

This would make refactoring existing code a bit easier as invalid types returned from mocks would be straight compile errors rather than test failures, thus failing faster and with (imo) a clearer error message.

@codyoss
Copy link
Member

codyoss commented Jul 10, 2020

Return operates on a Call today, which is what is returned by all of stubbed out methods. With how this library is currently designed, I don't this we can accommodate this request. If you have a concrete suggestion about how to implement this please feel free to reopen. Thanks.

@codyoss codyoss closed this as completed Jul 10, 2020
@robsonpeixoto
Copy link

@codyoss maybe minimock is a good inspiration.

@trim21
Copy link

trim21 commented Feb 3, 2022

@codyoss We can add a stub type in generated code to accomplish this, just like methods of Mock*MockRecorder:

source

type Auth interface {
	// GetByToken return an authorized user by a valid access token.
	GetByToken(ctx context.Context, token string) (model.User, error)
}

mocks

// Code generated by MockGen. DO NOT EDIT.

type MockAuthMockRecorder struct {
	...
}

// GetByToken indicates an expected call of GetByToken.
func (mr *MockAuthMockRecorder) GetByToken(ctx, token interface{}) *TypedCall {
	mr.mock.ctrl.T.Helper()
	return &TypedCall{mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByToken",
		reflect.TypeOf((*MockAuth)(nil).GetByToken), ctx, token)}
}


type TypedCall struct {
	*gomock.Call
}

func (t *TypedCall) Return(typedReturn1 model.User, typedReturn2 error) *gomock.Call {
	return t.Call.Return(typedReturn1, typedReturn2)
}

test

func TestTypeSafeReturn(t *testing.T) {
	m := NewMockAuth(gomock.NewController(t))
	m.GetByToken(gomock.Any(), gomock.Any()).Return() <== Now we get compile time error
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants