Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Field Type Matcher #237

Open
denizgursoy opened this issue Feb 16, 2025 · 0 comments
Open

Field Type Matcher #237

denizgursoy opened this issue Feb 16, 2025 · 0 comments

Comments

@denizgursoy
Copy link

Is it possible to add a matcher per type and use it? Whenever I use decimal.Decimal from github.com/shopspring/decimal as a field in in one of my structs, my mocks fail because precision in the type.

type MyType struct {
        Field1 string
	Field2 string
	Field3 decimal.Decimal
}
func Test_MyType(t *testing.T) {
	type MyType struct {
		Field1 string
		Field2 string
		Field3 decimal.Decimal
	}

	controller := gomock.NewController(t)
	client := NewMock(controller)
	client.EXPECT().MyFunction(gomock.Any(), MyType{}).Return().Times(1) // this fails
}

Is there a way to match these types in gomock?

If no, is there a way to extend gomock to match by specfic type in this case it is decimal.Decimal instead of writing a matcher for whole MyType struct

As a POC I did something like this:

func Test_MyType(t *testing.T) {
	type MyType struct {
		Field1 string
		Field2 string
		Field3 decimal.Decimal
	}

	decimalMatcher := DecimalMatcher{}
	controller := gomock.NewController(t, gomock.WithFieldMatcher[decimal.Decimal](decimalMatcher))
	client := NewMock(controller)
	client.EXPECT().MyFunction(gomock.Any(), MyType{}).Return().Times(1)
	fmt.Println(client)
}

type DecimalMatcher struct {
}

func (d DecimalMatcher) Matches(x any) bool {
	return true
}

func (d DecimalMatcher) String() string {
	return "foo"
}

This is for extending go mock whenever it sees a ``decimal.Decimal` type, it uses the custom matcher given instead of writing a new matcher for whole struct

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

No branches or pull requests

1 participant