golang / mock

GoMock is a mocking framework for the Go programming language.
Apache License 2.0
9.3k stars 611 forks source link

Custom Matcher #351

Closed Tylo-m closed 4 years ago

Tylo-m commented 4 years ago

Hi,

I want to validate only subfields of an object, sadly i did not find a way to do this using gomock. Is there a way to create a custom matcher ? for example passing a fonction f(interface...) bool that will contain the logic ?

If not is there any way i can do this using gomock ? :)

Thanks !

Tylo-m commented 4 years ago

Given the added tags i assume i was not clear in my first post. Let's try again :D.

Let's say i have a struct, this struct has multiple fields and is going to be passed to a method from a mocked service. But sadly within this struck some of the fields are generated "randomly" by another service that is not mocked and should not be.

Now what i would like to do if possible is to validate only a subset of this struct and ignore the "randomly" generated fields.

Is this possible ?

Thank you ! :)

rubens21 commented 4 years ago

It may be useful to you,

import "github.com/golang/mock/gomock"

func NewMatcher(customMatcher func(arg interface{}) bool) gomock.Matcher {
    return matcherCustomizer{customMatcher}
}

type matcherCustomizer struct {
    matcherFunction func(arg interface{}) bool
}

func (o matcherCustomizer) Matches(x interface{}) bool {
    return o.matcherFunction(x)
}

func (o matcherCustomizer) String() string {
    return "[call back function matcher has returned false]"
}

If you need an accurate error message, you may improve it to store an error message after the function be called.

Tylo-m commented 4 years ago

That is exactly what i wanted, Thanks you ! :)

codyoss commented 4 years ago

Thanks @rubens21 for helping out!

jtyers commented 4 years ago

Stumbled across this issue while looking for a way to do custom matchers. @codyoss could this be added to the README? Would make it much easier to find.