golang / mock

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

Mockgen: Support generating mock for interfaces that contain a generic typed return value #671

Closed CNLHC closed 1 year ago

CNLHC commented 1 year ago

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

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

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.

Why the feature is needed

This feature can help people test generic interfaces with the generic return types.

CNLHC commented 1 year ago

It seems that this feature request is related to https://github.com/golang/mock/issues/666

codyoss commented 1 year ago

This is implemented on HEAD, but has not been released. Please follow release milestone.