golang / mock

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

Mockgen: Support generating mock for interfaces with generics #621

Closed lingyv-li closed 2 years ago

lingyv-li commented 2 years ago

Requested feature

Mockgen should support generating mocks for interfaces with generics.

Why the feature is needed The Go 1.18 is planned to be released soon, and I noticed that the mockgen tool doesn't support the generic. When a type parameter is in the interface, mockgen will throw an error.

Code example: https://go.dev/play/p/g1G2OvZPQpT?v=gotip

> go run github.com/golang/mock/mockgen -source=generic_mock.go
2022/02/13 10:59:41 Loading input failed: don't know how to mock method of type *ast.IndexExpr
exit status 1

(Optional) Proposed solution

  1. In the code example above, the StudentRepository interface is concrete, so the gererated mock should be concrete too with the type parameters substituted.
  2. The BaseRepository interface is abstract, so the generated mock struct should also have the same type parameters.

(My use case only needs 1, which mockery supports as of today.)

codewith-luke commented 1 year ago

Even when trying with the 1.7.0-rc.1 I still get the same error message: Loading input failed: don't know how to mock method of type *ast.BinaryExpr

Getting the same issue too. Tried the main branch as well.

The issue seems to be happening when I have a constraint declaration:

type Number interface {
  int64 | float64
}

Similar to you I am seeing something along the lines of failed parsing returns: don't know how to parse type *ast.IndexExpr

This is when going over a just any reference to my generics such as a method in an interface:

Search(input InputInventorySearch) (*internal.Pagination[internal.Product], error)
tareksha commented 1 year ago

hi @codyoss , when is 1.7.0 expected to be released? go 1.18 was released over a year ago and large codebases started adopting generics.