Closed CNLHC closed 1 year ago
After #621 it is possible to generate a mock for interface with a generic type. But it seems that currently mockgen can not generate a mock for interfaces whose generic type is used in the method return value.
mockgen
Take the following code snippet as an example
package abstract import ( "context" ) type PathReader[T any] interface { IsDir() bool Key() string Raw() T } //go:generate mockgen -source=$GOFILE -destination=mocks/tree_viewer.go -package=mocks type TreeViewer[T any] interface { Root(ctx context.Context) (string, error) Children(context.Context, string) ([]PathReader[T], error) }
If the Children method returns ([]PathReader[T], error), the mockgen will throw an error like
Children
([]PathReader[T], error)
2022/08/09 15:32:05 Loading input failed: tree_viewer.go:16:10: failed parsing returns: don't know how to parse type *ast.IndexExpr integrate/abstract/tree_viewer.go:13: running "mockgen": exit status 1
Otherwise, if we change the return type to ([]any, error), the mockgen will work as expected.
([]any, error)
This feature can help people test generic interfaces with the generic return types.
It seems that this feature request is related to https://github.com/golang/mock/issues/666
This is implemented on HEAD, but has not been released. Please follow release milestone.
How this feature would be used.
After #621 it is possible to generate a mock for interface with a generic type. But it seems that currently
mockgen
can not generate a mock for interfaces whose generic type is used in the method return value.Take the following code snippet as an example
If the
Children
method returns([]PathReader[T], error)
, the mockgen will throw an error likeOtherwise, if we change the return type to
([]any, error)
, the mockgen will work as expected.Why the feature is needed
This feature can help people test generic interfaces with the generic return types.