golang / mock

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

Introduce possibility to list required interfaces so mockgen won't generate all of them in source mode #660

Open kliukovkin opened 2 years ago

kliukovkin commented 2 years ago

Requested feature Optional -interfaces flag for source mode so it will be possible to list only those interfaces that needed to be mocked.

Why the feature is needed Using reflect mode it is possible to list only required interfaces. For example, if there is a file with 3 different interfaces and the developer wants to generate mocks only for 2 of them it is not possible with go:generate annotation:

//go:generate mockgen -destination foo_mock.go -package myPackage -source file.go Foo
type Foo interface {}
//go:generate mockgen -destination bar_mock.go -package myPackage -source file.go Bar
type Bar interface {}
type Baz interface {}

Such an approach won't work cause there will be two generated files in the same package with the same content which includes all 3 interfaces. There also will be conflicts between these two files.

//go:generate mockgen -destination foo_mock.go -package myPackage -source file.go Foo, Bar
type Foo interface {}
type Bar interface {}
type Baz interface {}

The example above won't work also, there will be all 3 interface mocks in the generated file. (Optional) Proposed solution Introduce flag -interfaces which accepts a list of required interfaces separated by a comma. It will work like this:

//go:generate mockgen -destination foo_mock.go -package myPackage -source file.go -interfaces Foo
type Foo interface {}
//go:generate mockgen -destination bar_mock.go -package myPackage -source file.go -interfaces Bar
type Bar interface {}
type Baz interface {}

As a result, 2 files will be generated each containing a separate interface, Foo in foo_mock.go and Bar in bar_mock.go respectively. Also if we need Foo and Bar in a single generated file that will work also like this:

//go:generate mockgen -destination foo_mock.go -package myPackage -source file.go -interfaces Foo, Bar
type Foo interface {}
type Bar interface {}
type Baz interface {}
codyoss commented 2 years ago

Thanks for the request I will take a look at the PR shortly. Overall I think this is a good idea but could be tricky too with things like nested interfaces.

kliukovkin commented 2 years ago

@codyoss Hey! Did you have a chance to check the PR? I tested it with nested interfaces, seems like it is working as expected. Or could you specify the case, please?