golang/mock

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

CNLHC opened this issue · 2 comments

CNLHC commented

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

It seems that this feature request is related to #666

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